VB.NET 将 DataGridVIew 内容插入 SQL 服务器 table

VB.NET Insert DataGridVIew content into SQL Server table

我在将数据从我的 datagridview 插入我的 SQL 服务器 table

时遇到问题

我得到的错误是这样的:

System.Data.SqlClient.SqlException: The parameterized query '(@Articulo varchar(8000),@Cantidad varchar(8000),@Precio varchar' expects the parameter '@Articulo', which was not supplied.

我的代码:

Private Sub btnGetTotal_Click(sender As Object, e As EventArgs) Handles btnGetTotal.Click
    Dim connection As SqlConnection = New SqlConnection("xxx")
    Dim command As SqlCommand = New SqlCommand("INSERT INTO Ordenes_Full (Articulo, Cantidad, Precio) VALUES (@Articulo, @Cantidad, @Precio)")
    Dim dataAdapter As New Data.SqlClient.SqlDataAdapter
    Dim dataSet As New Data.DataSet

    command.Parameters.Add("@Articulo", SqlDbType.VarChar)
    command.Parameters.Add("@Cantidad", SqlDbType.VarChar)
    command.Parameters.Add("@Precio", SqlDbType.VarChar)

    connection.Open()
    command.Connection = connection

    For i As Integer = 0 To DataGridView1.Rows.Count - 1
        command.Parameters(0).Value = DataGridView1.Rows(i).Cells(0).Value
        command.Parameters(1).Value = DataGridView1.Rows(i).Cells(1).Value
        command.Parameters(2).Value = DataGridView1.Rows(i).Cells(2).Value
        command.ExecuteNonQuery()
    Next
 
End Sub

正如我在对该问题的评论中所建议的那样,我建议采取完全不同的做法。如果您要坚持使用此方法,则必须确保将“空”单元格作为 NULL 保存到数据库中。你可以这样做:

command.Parameters(0).Value = If(DataGridView1.Rows(i).Cells(0).Value, DBNull.Value)

这将使用单元格的 Value 除非它是 Nothing,在这种情况下它将使用 DBNull.Value

DBNull.Value 是 ADO.NET 用来表示数据库 NULL 的。它不能只使用 Nothing 的原因是因为 ADO.NET 是在可空值类型出现之前创建的。如果您使用 Nothing,例如,预期 Integer,那么它将被解释为零而不是 NULL