【发布时间】:2021-06-26 15:17:38
【问题描述】:
我有桌子
| itemID | storeID | qty |
|---|---|---|
| 103 | LAB | 20 |
我想添加特定项目的数量,例如:仓库'LAB'中存储的'103'。
public void addQuantity(string store, string item, int qty)
{
con.Open();
string sql = "SELECT qty,warehouse.storeID,item.itemID FROM Item,warehouse,stocker WHERE stocker.storeID=warehouse.storeID AND stocker.itemID=item.itemID AND warehouse.storeID='"+store+"' AND Item.itemID='"+item+"' ";
using (MySqlDataAdapter adapter = new MySqlDataAdapter(sql, con))
{
using (DataTable tempTable = new DataTable())
{
adapter.Fill(tempTable);
if (tempTable.Rows.Count == 0) throw new Exception("No such product");
foreach (DataRow r in tempTable.Rows)
{
int newQty = (int)r["qty"] + qty;
if (newQty > 0)
{
r["qty"] = newQty;
qty = 0;
break;
}
else
{
MessageBox.Show("error");
}
}
using (MySqlCommandBuilder cb = new MySqlCommandBuilder(adapter))
{
adapter.UpdateCommand = cb.GetUpdateCommand();// there is error
adapter.Update(tempTable);
}
}
}
con.Close();
}
它说:“多个基表不支持动态 SQL 生成”。
你有什么建议?
【问题讨论】:
-
旁注:不要使用字符串插值或连接将值获取到 SQL 查询中。这很容易出错,并且可能使您的程序容易受到 SQL 注入攻击。使用参数化查询。
-
和 explicit
JOIN语法将使查询至少更易于阅读和理解甚至编写。 -
我假设
itemid是item中的主键/键。使用它来处理您想要更改的item中的行并以这种方式构建UPDATE查询。