我今天做了一些重构,突然我的代码插入/更新了一个我记忆中已经工作的数据库表,不再工作,并抛出以下错误:
InvalidOperationException: Update requires a valid InsertCommand when passed DataRow collection with new rows.
代码如下:
' Update a field if it exists or insert a new row
' (should be an insert 99.99% of the time but not guaranteed)
Public Sub InsertOrUpdateValues(... multiple parameters ...)
Dim da As New SqlDataAdapter
Dim dt As New DataTable()
Dim dr As DataRow
Dim commandText As String = "select * from Table_Name where Col_Name1 = '" & value1 & "' AND Col_Name2 = '" & value2 & "'"
Dim sqlCommand As New SqlCommand(commandText, connection)
da.SelectCommand = sqlCommand
da.Fill(dt)
If dt.Rows.Count = 0 Then
dr = dt.NewRow()
dt.Rows.Add(dr)
Else
dr = dt.Rows(0)
End If
dr("Col_Name3") = value3
' ... more of these assignments ...
dr("Col_NameN") = valueN
da.Update(dt)
End Sub
我不确定破坏代码会发生什么。我看过this MSDN link,但我不确定如何将它应用到我使用DataTable
完成任务的方式。是否有“最佳实践”方法?
答案 0 :(得分:0)
我想我应该先进行一些搜索,因为我使用CommandBuilder
Dim commandBuilder As New SqlCommandBuilder(da)
If dt.Rows.Count = 0 Then
dr = dt.NewRow()
dt.Rows.Add(dr)
da.InsertCommand = commandBuilder.GetInsertCommand(True)
Else
dr = dt.Rows(0)
da.UpdateCommand = commandBuilder.GetUpdateCommand(True)
End If
我还为我的表/列名称添加了常量,以便于维护,现在使用带参数的查询。
Const commandText As String = "select * from " & Table.Name & " where " & Table.Column1 & " = @Value1 AND " & Table.Column2 & " = @Value2"
Dim sqlCommand As New SqlCommand(commandText, _connection)
sqlCommand.Parameters.Add("@Value1", SqlDbType.Type).Value = value1
sqlCommand.Parameters.Add("@Value2", SqlDbType.Type).Value = value2
这应该会更好一些,但如果您仍想发表评论,我仍然愿意接受更多建议。