到目前为止,我的代码只更新了一行,但有没有办法指定三行? (3个不同的ID')
Public Shared Sub UpdatePrice(ByVal NewPrice As Decimal, ByVal id As Integer)
Dim dtoffenseinfo As New DataTable
If Not DBConnection.State = ConnectionState.Open Then
'open connection
DBConnection.Open()
Else
End If
cmd.Connection = DBConnection
cmd.CommandText = "UPDATE tblStockPrice " & _
" SET Price=" & NewPrice & " WHERE id=" & id & ""
cmd.ExecuteNonQuery()
DBConnection.Close()
End Sub
我假设我需要为另外两行增加2个参数,这样就可以了。
答案 0 :(得分:0)
您可以使用一个带有相应UPDATE
子句的WHERE
语句来影响多个记录,但是,如果您想以不同方式影响每个记录,则调用ExecuteNonQuery
一次不是一个很好的选择。只需使用适当的参数创建一个命令,然后您可以多次设置每个参数的Value
以影响多个记录,例如
Using connection As New SqlConnection("connection string here"),
command As New SqlCommand("UPDATE MyTable SET Price = @Price WHERE Id = @Id", connection)
Dim priceParameter = command.Parameters.Add("@Price", SqlDbType.Money)
Dim idParameter = command.Parameters.Add("@Id", SqlDbType.Int)
Dim prices = {12.45, 132.67, 9.8}
Dim ids = {1, 19, 56}
connection.Open()
For i = 0 To 2
priceParameter.Value = prices(i)
idParameter.Value = ids(i)
command.ExecuteNonQuery()
Next
End Using