我遇到了一些奇怪的事情,我不确定为什么它会这样做。在for a循环中,我将行添加到表中以进行交叉引用。使用以下代码:
For Each cp In pCheckPoints
If cp <> String.Empty Then
Dim insertSQL As New StringBuilder
With insertSQL
.Append("INSERT INTO [CheckpointMessage] ( ")
.Append(" [MessageID] ")
.Append(", [CheckPoint] ")
.Append(" ) VALUES ( ")
.Append(" @MessageID ")
.Append(", @Checkpoint ")
.Append(" ) ")
End With
Using objCommand As New SqlCommand(insertSQL.ToString, MySQLConnection)
With objCommand.Parameters
.AddWithValue("@MessageID", pMessageID)
.AddWithValue("@Checkpoint", cp)
End With
objCommand.ExecuteNonQuery()
objCommand.CommandText = String.Empty
End Using
End If
Next
如果没有objCommand.CommandText = String.Empty行,CommandText会附加insertSQL,但这对我没有任何意义,因为我希望objCommand的commandText为空,因为它在using块中。
答案 0 :(得分:3)
您的命令文本每次都是相同的。不要重建它。试试这个:
Dim insertSql As String = _
"INSERT INTO [CheckpointMessage] " & _
"([MessageID], [CheckPoint]) " & _
"VALUES " & _
"(@MessageID, @ChceckPoint)"
Using cmd As New SqlCommand(insertSql, MySQLConnection)
cmd.Parameters.Add("@MessageID", SqlDbType.Int).Value = pMessageID
cmd.Parameters.Add("@CheckPoint", SqlDbType.NVarChar, 255) ''# I had to guess at this type
For Each cp As String In pCheckPoints.Where(Function(c) Not String.IsNullOrEmpty(c))
cmd.Parameters("@CheckPoint").Value = cp
cmd.ExecuteNonQuery()
Next cp
End Using
最好有很多原因:
答案 1 :(得分:0)
除了原始问题之外,以下几行不必在循环中
Dim insertSQL As New StringBuilder
With insertSQL
.Append("INSERT INTO [CheckpointMessage] ( ")
.Append(" [MessageID] ")
.Append(", [CheckPoint] ")
.Append(" ) VALUES ( ")
.Append(" @MessageID ")
.Append(", @Checkpoint ")
.Append(" ) ")
End With
Using objCommand As New SqlCommand(insertSQL.ToString, MySQLConnection)
您可以使用字符串一次创建带参数化查询的命令,并在循环中使用相同的objCommand
实例。循环中唯一属于动态值的东西。