System.Data.SqlClient.SqlException:“-”附近的语法不正确

时间:2018-12-16 08:16:42

标签: c# asp.net sql-server database

 SqlCommand command1 = connection.CreateCommand();
 command1.CommandType = CommandType.Text;
 command1.CommandText = "update product set product_qty=product_qty-"+t1.Text;
 command1.ExecuteNonQuery();

在购物车中,当我输入“ 2”并单击“添加到购物车”按钮时,说明中的“ product_qty”应更新为(OriginalQTY-2)。但是我得到这个上面的错误。请帮忙!

1 个答案:

答案 0 :(得分:2)

尝试使用参数。它使语法更清晰(并保护您免受SQL injection的攻击。)

还尝试使用[using]dispose个对象。

// using usings :-)
using (var connection = new SqlConnection(connectionstring))
using (var command1 = connection.CreateCommand())
{
     command1.CommandType = CommandType.Text;

     // your query with parameter: @qty
     // note 
     command1.CommandText = "update product set product_qty -=@qty";

     // setting a type: aka VarChar, Int etc, will make sure you 
     // don't mix up all the ' and "'s
     command1.Parameters.Add("@qty", SqlDbType.Int);

     // set parameter value: all values are safe.
     // since you are using an int, make sure you put in an int.
     // [note] int.Parse("some text other than a number like 3") 
     // will throw an exception
     command1.Parameters["@qty"].Value = int.Parse(t1.Text);

     // execute
     command1.ExecuteNonQuery();
}