【问题标题】:VB.Net insert multiple recordsVB.Net 插入多条记录
【发布时间】:2013-06-27 09:54:05
【问题描述】:

我在 DataGridView 控件中有几行。我想将每一行插入数据库。我试过这样。但是它给出了参数已经添加的错误。怎么加一次参数名,每次加值,每次都执行?

    Using connection As New SqlCeConnection(My.Settings.databaseConnectionString)
        Using command As New SqlCeCommand("INSERT INTO table_master(item, price) VALUES(@item, @price)", _
                                        connection)

            connection.Open()

            For Each r As DataGridViewRow In dgvMain.Rows
                If (Not String.IsNullOrWhiteSpace(r.Cells(1).Value)) Then
                    command.Parameters.AddWithValue("@item", r.Cells(1).Value.Trim)
                    command.Parameters.AddWithValue("@price", r.Cells(2).Value)


                    command.ExecuteNonQuery()
                End If
            Next

        End Using
    End Using

【问题讨论】:

    标签: sql vb.net


    【解决方案1】:

    在循环外添加参数,在循环内只更新它们的值

    Using connection As New SqlCeConnection(My.Settings.databaseConnectionString)
        Using command As New SqlCeCommand("INSERT INTO table_master(item, price) VALUES(@item, @price)", _
                                        connection)
    
            connection.Open()
    
            ' Create and add the parameters, just one time here with dummy values or'
            ' use the full syntax to create each single the parameter'
            command.Parameters.AddWithValue("@item", "")
            command.Parameters.AddWithValue("@price", 0)
    
            For Each r As DataGridViewRow In dgvMain.Rows
                If (Not String.IsNullOrWhiteSpace(r.Cells(1).Value)) Then
    
                    command.Parameters("@item").Value = r.Cells(1).Value.Trim
                    command.Parameters("@price").Value = r.Cells(2).Value
                    command.ExecuteNonQuery()
                End If
            Next
    
        End Using
    End Using
    

    使用 AddWithValue 是一个不错的快捷方式,但也有其缺点。例如,不清楚列Price 需要什么数据类型。使用 Parameter 构造函数,您可以为参数指定确切的数据类型并避免可能的转换错误

    Dim p = new SqlCeParameter("@price", SqlDbType.Decimal)
    command.Parameters.Add(p)
    ......
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-01
      • 2012-09-04
      • 2015-10-04
      • 2017-04-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多