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

C#开发简易库存系统:Sales表数据重复插入问题求助

问题诊断与修复:Sales表重复插入两次的原因

嘿,我一眼就发现你代码里的问题啦!你看这段关键代码:

int lastinsertID = int.Parse(cmd.ExecuteScalar().ToString());
cmd.ExecuteNonQuery();

你的SQL语句是insert into sales(subtoal,pay,bal) values(@subtoal,@pay,@bal); select @@identity;,ExecuteScalar()方法已经会完整执行这条SQL语句——它先执行INSERT插入一条Sales记录,然后返回@@IDENTITY的结果(也就是刚插入的自增ID)。而你紧接着又调用了cmd.ExecuteNonQuery(),这等于把同一条INSERT语句又执行了一遍,自然就生成了两条完全一样的Sales记录!

修复后的完整代码

把多余的cmd.ExecuteNonQuery()删掉就可以解决问题了,这里给你整理好修复后的代码,还顺便加了点资源优化的小细节:

// 建议用using语句自动管理连接和命令资源,避免泄漏
using (var con = new SqlConnection("你的数据库连接字符串"))
{
    string bal = txtBal.Text;
    string sub = txtSub.Text;
    string pay = textBox1.Text;
    string sql = "insert into sales(subtoal,pay,bal) values(@subtoal,@pay,@bal); select @@identity;";
    
    con.Open();
    using (var cmd = new SqlCommand(sql, con))
    {
        cmd.Parameters.AddWithValue("@subtoal", sub);
        cmd.Parameters.AddWithValue("@pay", pay);
        cmd.Parameters.AddWithValue("@bal", bal);
        // ExecuteScalar已经执行了INSERT,直接获取自增ID即可
        int lastinsertID = int.Parse(cmd.ExecuteScalar().ToString());

        // 循环插入sales_product记录
        for (int row = 0; row < dataGridView1.Rows.Count; row++)
        {
            // 跳过DataGridView的空行(如果有的话)
            if (dataGridView1.Rows[row].IsNewRow) continue;
            
            string proddname = dataGridView1.Rows[row].Cells[0].Value.ToString();
            int price = int.Parse(dataGridView1.Rows[row].Cells[1].Value.ToString());
            int qty = int.Parse(dataGridView1.Rows[row].Cells[2].Value.ToString());
            int total = int.Parse(dataGridView1.Rows[row].Cells[3].Value.ToString());
            
            string sql1 = "insert into sales_product(sales_id,prodname,price,qty,total) values(@sales_id,@prodname,@price,@qty,@total)";
            using (var cmd1 = new SqlCommand(sql1, con))
            {
                cmd1.Parameters.AddWithValue("@sales_id", lastinsertID);
                cmd1.Parameters.AddWithValue("@prodname", proddname);
                cmd1.Parameters.AddWithValue("@price", price);
                cmd1.Parameters.AddWithValue("@qty", qty);
                cmd1.Parameters.AddWithValue("@total", total);
                cmd1.ExecuteNonQuery();
            }
        }
    }
    MessageBox.Show("Record Added Successfully!");
}

几个关键说明

  1. 移除多余的ExecuteNonQuery():这是解决重复插入的核心,ExecuteScalar()已经完成了INSERT操作,不需要再重复执行。
  2. 用using语句管理资源:SqlConnection、SqlCommand都实现了IDisposable接口,用using可以自动释放资源,避免数据库连接泄漏。
  3. 跳过DataGridView空行:加上if (dataGridView1.Rows[row].IsNewRow) continue;可以避免插入空的产品记录。

内容的提问来源于stack exchange,提问作者jaya priya

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:29:42