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

DataGrid数据存入tblDetallePresupuesto表重复两条相同记录问题

问题原因与修复方案

核心问题分析

出现重复/错误插入的原因有两个:

  • 变量累加错误:你用+=对detalleCantidad、detalleDetalle等变量赋值,导致这些变量会持续叠加所有行的数据,而非当前行的独立值。比如第二行插入的是第一行+第二行的累加数据,看起来就像重复记录。
  • 重复添加参数:每次循环都执行cmd2.Parameters.Add,会不断给命令对象新增参数。OleDb参数按顺序绑定,参数数量超出SQL占位符后,会导致值匹配混乱,最终插入错误数据。

修复后的代码

Private Sub AgregarDetalle()
    ' Agregar Detalle del Presupuesto a la tabla secundaria
    AbrirConexion()
    Dim cmd2 As New OleDb.OleDbCommand("INSERT INTO tblDetallePresupuesto (Numero, Cantidad, Descripcion, PrecioUnitario, PrecioFinal) values(@Numero, @Cantidad, @Descripcion, @PrecioUnitario, @PrecioFinal)", Conexion)
    
    ' 提前定义所有参数,避免循环内重复添加
    cmd2.Parameters.Add("@Numero", OleDb.OleDbType.Double)
    cmd2.Parameters.Add("@Cantidad", OleDb.OleDbType.Integer)
    cmd2.Parameters.Add("@Descripcion", OleDb.OleDbType.VarChar)
    cmd2.Parameters.Add("@PrecioUnitario", OleDb.OleDbType.Integer)
    cmd2.Parameters.Add("@PrecioFinal", OleDb.OleDbType.Integer)

    ' 遍历DataGrid的每一行,插入单独记录
    For i = 0 To dtgProductos.Rows.Count - 1
        ' 直接获取当前行的单元格值,不再累加
        cmd2.Parameters("@Numero").Value = detalleNumero
        cmd2.Parameters("@Cantidad").Value = dtgProductos.Rows(i).Cells(0).Value
        cmd2.Parameters("@Descripcion").Value = dtgProductos.Rows(i).Cells(1).Value
        cmd2.Parameters("@PrecioUnitario").Value = dtgProductos.Rows(i).Cells(2).Value
        cmd2.Parameters("@PrecioFinal").Value = dtgProductos.Rows(i).Cells(3).Value
        
        cmd2.ExecuteNonQuery()
    Next

    Conexion.Close()
End Sub

关键修复点说明

  1. 参数定义移至循环外:只在循环前定义一次所有参数,避免重复添加导致的参数绑定混乱。
  2. 取消变量累加:直接读取当前行的单元格值赋值给参数,确保每一行插入的都是该行的独立数据。
  3. 统一参数值更新:循环内仅更新已有参数的Value属性,保证每次插入的都是当前行的正确数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 00:10:28