You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

点击按钮更新tbProduct库存数量报错,求解决方案(含DataGridView窗体)

问题描述

我有两个带有DataGridView的窗体formproduct和formorder,需求是点击按钮后从tbProduct表的库存数量中减去销售数量并更新表数据。编写的C#操作SQL Server代码如下:

cm = new SqlCommand("SELECT * FROM tbProduct ", con);
long var_stock = 0;
long var_sell = 0;
long result = 0;
var_stock = Convert.ToInt64(numericUpDown1.Value);
var_sell = qty;
result = var_stock - var_sell;
cm = new SqlCommand("UPDATE tbProduct SET pqty = @pqty '" + result+ "' WHERE pid LIKE '" + txtPid + "' ", con);
   
con.Open();
cm.ExecuteNonQuery();
con.Close();
   
this.Dispose();

运行时出现错误提示:

must declare the scalar variable @ptqy+

解决方案

你的代码存在语法错误、库存获取逻辑错误,还存在SQL注入风险,具体修正如下:

核心问题分析

  1. SQL语法错误:你错误地将参数占位符@pqty和变量result拼接,导致SQL Server将@pqty识别为未声明的标量变量,同时字符串拼接产生了无效的SQL语句。
  2. 库存获取错误:执行了SELECT * FROM tbProduct但未读取数据,直接用numericUpDown1.Value作为库存,这会导致计算基于过时的本地数据,而非数据库最新库存。
  3. SQL注入风险:直接拼接txtPid到SQL语句中,存在被注入攻击的风险。

修正后的代码

// 获取数据库中当前商品的最新库存
long currentStock = 0;
using (SqlCommand getStockCmd = new SqlCommand("SELECT pqty FROM tbProduct WHERE pid = @pid", con))
{
    getStockCmd.Parameters.AddWithValue("@pid", txtPid.Text);
    con.Open();
    var stockResult = getStockCmd.ExecuteScalar();
    if (stockResult != DBNull.Value)
    {
        currentStock = Convert.ToInt64(stockResult);
    }
    con.Close();
}

// 计算更新后的库存(可添加库存不能为负的校验)
long updatedStock = currentStock - qty;

// 执行库存更新
using (SqlCommand updateCmd = new SqlCommand("UPDATE tbProduct SET pqty = @updatedStock WHERE pid = @pid", con))
{
    updateCmd.Parameters.AddWithValue("@updatedStock", updatedStock);
    updateCmd.Parameters.AddWithValue("@pid", txtPid.Text);
    con.Open();
    updateCmd.ExecuteNonQuery();
    con.Close();
}

this.Dispose();

额外优化建议

  • 使用using语句自动释放SqlCommand资源,避免内存泄漏
  • 添加库存合法性校验(如updatedStock >= 0,防止负库存)
  • 增加异常捕获逻辑,处理数据库连接失败、数据转换错误等情况

内容的提问来源于stack exchange,提问作者zazo mama

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 11:02:27