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

从VB.NET DataGridView向SQL Server插入数据时参数缺失报错

问题解决:参数化查询提示未提供@EmpName但记录已插入

错误原因分析

你的代码能插入记录但报错,核心问题是DataGridView默认包含一行空的新增行(AllowUserToAddRows属性默认是True),当循环执行到这一行时,DataGridView1.Rows(i).Cells(0).Value为Nothing/DBNull,导致参数@EmpName未被正确赋值,触发SQL Server的参数缺失错误。

另外你的SQL语句里参数@otherUSDEarnings是小写开头,和代码中添加的@OtherUSDEarnings大小写不一致(虽然SQL Server参数不区分大小写,但这是不规范写法,建议统一)。

修复后的代码

Dim connetionString As String = "Data Source=Server\SQlExpress;Initial Catalog=CreSolDemo;User ID=sa;Password=Mkwn@011255"

' 使用Using语句自动释放连接和命令资源,避免泄漏
Using cnn As New SqlConnection(connetionString),
      cmd As New Data.SqlClient.SqlCommand("INSERT INTO TempPeriodTrans (EmpName, USDBasic, OtherUSDEarnings, ZDollarBasic, OtherZDEarnings) VALUES (@EmpName, @USDBasic, @OtherUSDEarnings, @ZDollarBasic, @OtherZDEarnings)", cnn)

    ' 给参数指定大小,避免默认的8000长度浪费资源
    cmd.Parameters.Add("@EmpName", SqlDbType.VarChar, 100)
    cmd.Parameters.Add("@USDBasic", SqlDbType.VarChar, 50)
    cmd.Parameters.Add("@OtherUSDEarnings", SqlDbType.VarChar, 50)
    cmd.Parameters.Add("@ZDollarBasic", SqlDbType.VarChar, 50)
    cmd.Parameters.Add("@OtherZDEarnings", SqlDbType.VarChar, 50)

    cnn.Open()

    ' 排除最后一行空的新增行,循环到Rows.Count - 2
    For i As Integer = 0 To DataGridView1.Rows.Count - 2
        ' 处理单元格值为Null的情况,赋值DBNull.Value避免参数未初始化
        cmd.Parameters("@EmpName").Value = If(DataGridView1.Rows(i).Cells(0).Value Is Nothing, DBNull.Value, DataGridView1.Rows(i).Cells(0).Value)
        cmd.Parameters("@USDBasic").Value = If(DataGridView1.Rows(i).Cells(1).Value Is Nothing, DBNull.Value, DataGridView1.Rows(i).Cells(1).Value)
        cmd.Parameters("@OtherUSDEarnings").Value = If(DataGridView1.Rows(i).Cells(2).Value Is Nothing, DBNull.Value, DataGridView1.Rows(i).Cells(2).Value)
        cmd.Parameters("@ZDollarBasic").Value = If(DataGridView1.Rows(i).Cells(3).Value Is Nothing, DBNull.Value, DataGridView1.Rows(i).Cells(3).Value)
        cmd.Parameters("@OtherZDEarnings").Value = If(DataGridView1.Rows(i).Cells(4).Value Is Nothing, DBNull.Value, DataGridView1.Rows(i).Cells(4).Value)

        cmd.ExecuteNonQuery()
    Next
End Using

MsgBox("Record saved")

关键修复点

  • 排除空新增行:循环条件改为Rows.Count - 2,跳过DataGridView默认的空新增行
  • 处理Null值:使用If判断单元格值,为空时赋值DBNull.Value,确保参数始终有有效值
  • 使用Using语句:自动释放数据库连接和命令资源,避免内存泄漏和连接池耗尽
  • 统一参数名大小写:SQL语句和参数添加的名称保持一致,避免潜在问题
  • 指定参数大小:明确VarChar的长度,避免默认的8000字符长度浪费数据库资源

内容的提问来源于stack exchange,提问作者Charm Mukuwane

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 03:45:52