VB.NET循环执行MySqlCommand的ExecuteNonQuery卡住报错求助
问题根因分析
- 循环内重复创建数据库连接:每轮循环都新建
MySqlConnection对象,短时间内创建大量连接容易触发MySQL连接数限制,也会导致连接资源未及时释放,引发结果集读取异常 - 参数类型不匹配:使用了SQL Server专属的
SqlDbType.VarChar枚举作为MySQL参数类型,类型不匹配导致驱动解析命令出错 - 参数残留问题:每轮循环没有清空命令对象的参数集合,上一轮的参数残留会导致命令结构异常
- 冗余连接占用资源:代码开头声明的
connTmp全程未使用,一直处于打开状态占用连接资源
修复方案
步骤1:优化连接逻辑,全程复用单个连接,避免循环内反复创建销毁连接
步骤2:替换为MySQL专属的参数类型枚举MySqlDbType
步骤3:每轮循环使用新的命令对象,避免参数残留
步骤4:删除无用的冗余连接声明
修复后参考代码
Dim X As Integer Dim stMp As String ' 全程复用单个连接,减少资源消耗 Using connt1 As MySqlConnection = New MySqlConnection(ConnString) connt1.Open() For X = 0 To GridView3.RowCount - 1 stMp = "" Select Case GridView3.GetRowCellValue(X, "col6").ToString Case "M01" 'customer stMp = "UPDATE tbuser SET fcust_a=@value_a,fcust_e=@value_e,fcust_d=@value_d,fcust_v=@value_v WHERE fuser=@userid" Case "M02" 'supplier stMp = "UPDATE tbuser SET fsupp_a=@value_a,fsupp_e=@value_e,fsupp_d=@value_d,fsupp_v=@value_v WHERE fuser=@userid" Case "M03" 'salesman ' 其余case保持原有逻辑不变 ' 其余case省略 End Select Try If stMp.Length > 0 Then Using mysqlcmd As MySqlCommand = New MySqlCommand(stMp, connt1) ' 每轮使用全新参数集合,避免参数残留 With mysqlcmd.Parameters .AddWithValue("@value_a", CInt(GridView3.GetRowCellValue(X, "col2"))) .AddWithValue("@value_e", CInt(GridView3.GetRowCellValue(X, "col3"))) .AddWithValue("@value_d", CInt(GridView3.GetRowCellValue(X, "col4"))) .AddWithValue("@value_v", CInt(GridView3.GetRowCellValue(X, "col5"))) ' 使用MySQL专属类型枚举 .Add("@userid", MySqlDbType.VarChar, 50).Value = sUser End With mysqlcmd.ExecuteNonQuery() End Using End If Catch ex As Exception ' 输出完整错误信息方便后续排查 MessageBox.Show(Me, ex.ToString()) End Try Next X End Using
额外优化建议
- 行数较多时可以开启事务批量提交所有更新,既可以提升执行效率,也能保证数据一致性
- 读取GridView单元格值时先判断是否为
DBNull,避免空值触发类型转换报错
内容的提问来源于stack exchange,提问作者Imam
相关产品推荐
相关产品推荐

