【问题标题】:How to modify specific cell value mysql table in c#?如何在c#中修改特定的单元格值mysql表?
【发布时间】: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 语法将使查询至少更易于阅读和理解甚至编写。
  • 我假设itemiditem 中的主键/键。使用它来处理您想要更改的item 中的行并以这种方式构建UPDATE 查询。

标签: c# mysql .net database


【解决方案1】:

如果qty是整数列,你可以尝试:

将其当前值增加某个值:

using (var updateCommand = new MySqlCommand())
{
    updateCommand.CommandText = "UPDATE mytable t SET t.qty = t.qty + @newQty WHERE *...Your WHERE clause...*`"
    updateCommand.Parameters.AddWithValue("@newQty", newQtyValue);`
    // ...
}

或者追加全新的值:

using (var updateCommand = new MySqlCommand())
{
    updateCommand.CommandText = "UPDATE mytable t SET t.qty = @newQtyValue WHERE *...Your WHERE clause...*`"
    updateCommand.Parameters.AddWithValue("@newQtyValue", newQtyValue);`
    // ...
}

正如@sticky bit所说,最好使用Command.Parameters.AddWithValue而不是字符串连接/插值。

【讨论】:

猜你喜欢
  • 2014-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-22
  • 1970-01-01
  • 2019-08-06
相关资源
最近更新 更多