【发布时间】:2015-06-08 14:39:37
【问题描述】:
我想更新大约 50 行。所以我在foreach中做 代码运行没有任何错误,但数据库中没有任何变化。
public void updateItems(List<product> prdList)
{
MySqlTransaction tr = null;
try
{
tr = this.con.BeginTransaction();
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = con;
cmd.Transaction = tr;
foreach (product prd in prdList)
{
cmd.CommandText = "UPDATE products SET title='@title', quantity='@quantity' WHERE itemId LIKE '@itemId'";
cmd.Parameters.AddWithValue("@title", prd.title);
cmd.Parameters.AddWithValue("@quantity", prd.quantity);
cmd.Parameters.AddWithValue("@itemId", prd.itemId);
cmd.ExecuteNonQuery();
}
tr.Commit();
}
catch (MySqlException ex)
{
try
{
tr.Rollback();
}
catch (MySqlException ex1)
{
MessageBox.Show(ex1.ToString());
}
MessageBox.Show(ex.ToString());
}
}
如果我打印查询字符串并在 SQL-Bash 上运行它,它工作正常。
【问题讨论】:
-
你引用了你的参数。那是错的。参数进入“裸体”,从不引用。
set title=@title,不是set title='@title'。 -
不要使用
AddWithValue,具体说明您要添加的类型。
标签: c# mysql transactions