2013-06-27 185 views
4

我在DataGridView控件中有几行。我想将每一行插入到数据库中。我试过这样。但它给出了错误,该参数已被添加。如何一次添加参数名称,然后每次添加值并每次执行?VB.Net插入多条记录

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 

回答

5

添加参数仅环它们的值

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需要哪种数据类型。使用参数构造函数,您可以指定参数的确切数据类型,并避免可能的转换错误

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

像魅力一样工作。谢谢 –