小编典典

VB.Net插入多个记录

sql

我在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

阅读 168

收藏
2021-05-23

共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是一个不错的捷径,但有其缺点。例如,不清楚column所需的数据类型是什么Price。使用Parameter构造函数,您可以为参数指定确切的数据类型,并避免可能的转换错误

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