我有一个数据网格,其中有很多行。我只想获取2列,其中一列将从中搜索具有该值的该行的数据库,第二列将使用新值更新该行。请帮忙。
我的代码出现语法错误
关键字“VALUES”
附近的语法不正确
我的代码
{
using (SqlConnection con = new System.Data.SqlClient.SqlConnection("Data Source=rex;Initial Catalog=PersonalDetails;Integrated Security=True"))
{
con.Open();
for (int i = 0; i <= dataGridView2.Rows.Count - 1; i++)
{
String insertData = "UPDATE Test SET AvailableQty = " + "VALUES (@Qty) Where ItemCode = " + "VALUES (@ItemCode) ";
SqlCommand cmd = new SqlCommand(insertData, con);
cmd.Parameters.AddWithValue("@ItemCode", dataGridView2.Rows[i].Cells[0].Value ?? DBNull.Value);
cmd.Parameters.AddWithValue("@Qty", dataGridView2.Rows[i].Cells[4].Value ?? DBNull.Value);
cmd.ExecuteNonQuery();
}
}
}
答案 0 :(得分:0)
您有错误的更新查询更改您的查询,如
String insertData = "UPDATE Test SET AvailableQty = @Qty Where ItemCode = @ItemCode";
了解更多信息click here
要从availableQty
获取database
,请使用选择查询,例如
Select availableQty from tablename where `use here primary value column and it's value'
就像我将id
作为值为1
的主列,然后我写
Select availableQty from tablename where id = 1
获得价值后,您可以轻松地减去
double substractval = availableQty - dataGridView2.Rows[i].Cells[4].Value;
现在最后使用您的update
查询
Update tablename set availableQty = '"+substractval +"' where "pass primary column and value
您必须使用此类方案。 希望你理解并为你工作。
答案 1 :(得分:0)
首先,您应该始终使用 parameterized queries 。这种代码对SQL Injection攻击开放。
我认为您误解了T-SQL
中Update的语法。
using (SqlConnection con = new System.Data.SqlClient.SqlConnection("Data Source=rex;Initial Catalog=PersonalDetails;Integrated Security=True"))
{
con.Open();
for (int i = 0; i <= dataGridView2.Rows.Count - 1; i++)
{
string insertData = "UPDATE Test SET AvailableQty = @Qty Where ItemCode = @ItemCode";
SqlCommand cmd = new SqlCommand(insertData, con);
cmd.Parameters.AddWithValue("@ItemCode", dataGridView2.Rows[i].Cells[0].Value ?? DBNull.Value);
cmd.Parameters.AddWithValue("@Qty", dataGridView2.Rows[i].Cells[4].Value ?? DBNull.Value);
cmd.ExecuteNonQuery();
}
}
答案 2 :(得分:0)
您的查询字符串错误,这就是为什么它会给您一个语法错误:
string insertData = "UPDATE Test SET AvailableQty = @Qty WHERE ItemCode = @ItemCode";
请尽量避免使用String
课程:look here。