C# System.Data.SqlClient.SqlException:靠近'的语法不正确-';

C# System.Data.SqlClient.SqlException:靠近'的语法不正确-';,c#,asp.net,sql-server,database,C#,Asp.net,Sql Server,Database,在购物车中,当我输入“2”并单击“添加到购物车”按钮时,说明中的“产品数量”应更新为(原始数量-2)。但是我得到了上面的错误。请帮忙 尝试使用参数。它使语法更清晰(并保护您免受攻击) 也尝试使用,以便对对象进行修改 SqlCommand command1 = connection.CreateCommand(); command1.CommandType = CommandType.Text; command1.CommandText = "update product set produ

在购物车中,当我输入“2”并单击“添加到购物车”按钮时,说明中的“产品数量”应更新为(原始数量-2)。但是我得到了上面的错误。请帮忙

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

也尝试使用,以便对对象进行修改

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

检查后面的双引号--您不应该将SQL语句连接在一起-使用参数化查询来避免SQL注入-还请注意,SqlCommand是IDisposable的,因此应该位于
using
块中。注意:创建参数会返回对参数的引用,因此无需重复引用两次:和command1.CommandText=“更新产品集product_qty-=@qty”;parameter.value=.value=t1.Text;首先,非常感谢您的回复。但是,我仍然收到错误“输入字符串格式不正确”,并且数量应该是int,而不是var char(我已经更改了):)@WYMOWaiYan:嗨,我更新了一点,现在应该可以用了。虽然我没有测试;-)@MitchWheat:谢谢提醒。我想我终于明白OP的意思了。XD@Stefan感谢您的友好回复。遗憾的是,输入的格式仍然不正确:(
// 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();
}