1

我的 SQL Server 2008 数据库有一个带有 datatype 列的表datetime

当我尝试将值插入到datetime列中时,出现错误。

'-' 附近的语法不正确

我的日期时间选择器具有自定义格式,yyyy-MM-dd例如 (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 + "#,");

请问有人有想法吗?

4

3 回答 3

1

将日期用单引号而不是 # 括起来。

此字符串连接是等待发生的 SQL 注入。改用带参数的SqlCommand,就不用担心字符串转换的问题了

于 2012-11-01T01:22:25.800 回答
1

首先:停止将您的 SQL 代码连接在一起!这是对 SQL 注入攻击的邀请,而且对性能也非常不利 - 请改用参数化查询

如果你这样做 - 你也不会遇到日期时间/字符串转换问题......

DateTime其次: SQL Server 中仅日期的“安全”格式是YYYYMMDD-没有任何破折号- 只有这种格式才能保证它可以在任何 SQL Server 上运行,无论您的语言、区域和日期格式设置如何。

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

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();
}

Don't use EXEC ...... as an inline SQL statement - tell ADO.NET that you're executing a stored procedure, supply the parameters - and you're done!

于 2012-11-01T05:57:29.897 回答
0

试试这个

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

或者

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);
于 2012-11-01T01:28:47.113 回答