2012-11-01 145 views
1

我的SQL Server 2008数据库有一个表格,其中有一列数据类型为datetime如何将日期选择器日期时间值插入到sql数据库中

当我尝试将值插入datetime列时,我收到错误消息。

附近有语法错误 - “

我的日期时间选择器具有自定义格式yyyy-MM-dd e.g(2012-11-01)

以下是我用来插入datetime代码示例。

System.DateTime myDate = default(System.DateTime); 
myDate = DateTimePickerPrint.Value; 
string query = string.Format("EXEC Save_Quotation_Bookshop '" + txt_QutationNo.Text + "','" + txt_CusCode.Text + "',#" + myDate + "#,"); 

请任何人有一个想法?

回答

1

第一关:STOP串联起来你的SQL代码!这是针对SQL注入攻击的邀请,它对性能也非常不利 - 使用参数化查询代替。

如果你这样做 - 你不会有日期时间/串转换问题,无论问题.....

其次:约会,只DateTime“安全”的格式在SQL Server是YYYYMMDD - 没有任何破折号 - 只有这种格式保证它可以在任何SQL Server上运行,无论您的语言,地区和dateformat设置如何。

第三。如果要执行存储过程 - 我会建议使用这种方法:

System.DateTime myDate = default(System.DateTime); 
myDate = DateTimePickerPrint.Value; 

using (SqlConnection con = new SqlConnection(your-connection-string-here)) 
using (SqlCommand cmd = new SqlCommand("dbo.Save_Quotation_Bookshop", con)) 
{ 
    // tell ADO.NET it's a stored procedure (not inline SQL statements) 
    cmd.CommandType = CommandType.StoredProcedure; 

    // define parameters 
    cmd.Parameters.Add("@QuotationNo", SqlDbType.VarChar, 50).Value = txt_QutationNo.Text; 
    cmd.Parameters.Add("@CustomerCode", SqlDbtype.VarChar, 25).Value = txt_CusCode.Text; 
    cmd.Parameters.Add("@SaleDate", SqlDbType.DataTime).Value = myDate; 

    // open connection, execute stored procedure, close connection again 
    con.Open(); 
    cmd.ExecuteNonQuery(); 
    con.Close(); 
} 

不要使用为嵌入式SQL语句 - 告诉你执行存储过程ADO.NET,提供参数 - 你完成了!

+0

thnx用于回复,其工作方式是通过删除EXEC ADO.NET,并执行完整的ADO.NET – las

1

将日期换成单引号而不是#。

该字符串连接是一个SQL注入等待发生。使用SqlCommand时使用的参数,而不是,那么你不必担心字符串转换问题

+0

thnx回复,我用SqlCommand参数,但它给出了以下错误。但是,你可以把一个代码样本换成单引号而不是# – las

+0

不允许将数据类型的日期时间隐式转换为十进制。使用CONVERT函数来运行这个查询 – las

0

试试这个

string query = String.Format("EXEC Save_Quotation_Bookshop '{0}','{1}','{2}'",txt_QutationNo.Text,txt_CusCode.Text, myDate); 

OR

string query = string.Format("EXEC Save_Quotation_Bookshop @QutationNo,@CusCode,@myDate"); 

... 
comm.Parameters.AddWithValue("@QutationNo", txt_QutationNo.Text); 
comm.Parameters.AddWithValue("@CusCode", txt_CusCode.Text); 
comm.Parameters.AddWithValue("@myDate", myDate); 
+0

我试过了,但是当我把单一的qutation给出错误:将数据类型varchar转换为decimal时出错。 – las

+0

确保您按照各自的顺序排列每个参数 – codingbiz

+0

Thnx以回复@codingbiz。我会试试这个。 – las

相关问题