如何通过ComboBox选择项累加更新数据库行中商品的数量
解决商品数量累加更新的问题
核心UPDATE语句逻辑
MySQL中实现数量累加的语法是直接在UPDATE语句中对字段进行算术运算,将现有数量与新增数量相加:
UPDATE canned_goods SET quantity = quantity + @addQuantity WHERE item = @selectedItem;
其中@addQuantity是输入的新增数量,@selectedItem是ComboBox选中的商品名称。
完整代码修改与实现
- 修正全局的update字符串:
string update = "UPDATE canned_goods SET quantity = quantity + @addQuantity WHERE item = @selectedItem";
- 新增更新按钮的点击事件(假设你添加了名为
buttonUpdate的按钮):
private void buttonUpdate_Click(object sender, EventArgs e) { // 检查ComboBox是否选中商品 if (comboBox1.SelectedItem == null) { MessageBox.Show("请先选择要更新的商品"); return; } // 获取选中的商品名称 DataRowView selectedRow = (DataRowView)comboBox1.SelectedItem; string selectedItem = selectedRow["item"].ToString(); // 获取输入的新增数量 long addQuantity = Convert.ToInt64(numericUpDown1.Value); try { con.Open(); cmd = new MySqlCommand(update, con); // 添加参数避免SQL注入 cmd.Parameters.Add("@selectedItem", MySqlDbType.VarChar).Value = selectedItem; cmd.Parameters.Add("@addQuantity", MySqlDbType.Int64).Value = addQuantity; int affectedRows = cmd.ExecuteNonQuery(); if (affectedRows > 0) { MessageBox.Show("数量更新成功"); // 刷新界面数据 sql = "SELECT item FROM `canned_goods`"; fillDataComboBox(sql, comboBox1); fillItemListBox(sql, listBoxItem); fillQuantityListBox(sql, listBoxQuantity); } else { MessageBox.Show("未找到对应商品,更新失败"); } } catch (Exception err) { MessageBox.Show("更新错误:" + err.Message); } finally { cmd.Dispose(); con.Close(); } }
- 关键注意事项:
- 确保
canned_goods表中item字段唯一,否则会更新所有同名商品的数量;若存在同名商品,建议改用唯一ID字段作为匹配条件。 - 全局复用
MySqlConnection存在连接泄漏风险,建议在操作方法内用using语句创建新连接实例,比如:using (MySqlConnection con = new MySqlConnection("你的连接字符串"))。 - 更新完成后务必刷新界面列表,保证数据显示同步。
内容的提问来源于stack exchange,提问作者Nicholas Wallace
相关产品推荐
相关产品推荐

