C# 如何在SQL Server中插入时间列
使用VisualStudio2010和C#C# 如何在SQL Server中插入时间列,c#,asp.net,sql-server,datetime,C#,Asp.net,Sql Server,Datetime,使用VisualStudio2010和C# 表1: column datatype ------------------------ Currenttime time 如何将时间值插入表1 代码 获取错误 无法从字符串转换为System.Timespan 插入表1时 需要代码帮助您需要DateTime.Parse而不是Timespan.Parse,Timespan表示时间长度您需要解析DateTime而不是datetimepicker本身,解析其值 DateTime.Pa
表1
:
column datatype
------------------------
Currenttime time
如何将时间值插入表1
代码
获取错误
无法从字符串转换为System.Timespan
插入表1时
需要代码帮助您需要DateTime.Parse而不是Timespan.Parse,Timespan表示时间长度您需要解析DateTime而不是datetimepicker本身,解析其值
DateTime.Parse(datetimepicker1.value)
您应该始终(没有例外!)使用参数化查询,而不是将自己的SQL语句构造为字符串!只是谷歌“SQL注入”——这真是一件可怕的事情立即停止这样做
要使用参数化查询,您应该养成使用以下模式的习惯:
// Define your SQL query - WITH parameters!
// And always specify the list of columns for your INSERT!
string query = "INSERT INTO dbo.Table1(CurrentTime) VALUES(@TimeValue)";
// use the "using" blocks to properly protect your disposable connection and command
using (SqlConnection con = new SqlConnection("server=.;database=test;integrated security=SSPI;"))
using (SqlCommand cmd = new SqlCommand(query, con))
{
string hr = txtHr.Text;
string min = txtMin.Text;
string time = hr + ":" + min;
// set the parameter value
cmd.Parameters.Add("@TimeValue", SqlDbType.Time).Value = TimeSpan.Parse(time);
// open connection, execute your INSERT, close connection
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
你能把错误写在这里吗?是转换错误吗?@Rapunzlo,由于无法从system.datetime转换到system.timespanYou应该始终使用参数化查询,而不是将自己的SQL语句连接在一起(没有例外!)@marcs,这是一个预定义的表,我无法编辑结构,如何在c#中转换您不必更改表中的任何内容-只需更改您的编程习惯尝试,获取错误无法转换为system.datetime到system.TimesPana获取相同的错误,我已编辑了我的问题并添加了代码,请检查并帮助我
// Define your SQL query - WITH parameters!
// And always specify the list of columns for your INSERT!
string query = "INSERT INTO dbo.Table1(CurrentTime) VALUES(@TimeValue)";
// use the "using" blocks to properly protect your disposable connection and command
using (SqlConnection con = new SqlConnection("server=.;database=test;integrated security=SSPI;"))
using (SqlCommand cmd = new SqlCommand(query, con))
{
string hr = txtHr.Text;
string min = txtMin.Text;
string time = hr + ":" + min;
// set the parameter value
cmd.Parameters.Add("@TimeValue", SqlDbType.Time).Value = TimeSpan.Parse(time);
// open connection, execute your INSERT, close connection
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}