SQLCommand 不清除循环中的命令文本
我遇到了一些奇怪的事情,我不确定为什么会这样。在 foreach 循环中,我将行添加到表中以供交叉引用。使用以下代码:
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 块中。
I ran into something odd, and I'm not precisely sure why it is behaving this way. In a for each loop I am adding rows to a table for a cross reference. Using the following code:
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
Without the objCommand.CommandText = String.Empty line the CommandText is appending the insertSQL but that doesn't make any sense to me because I would expect the objCommand's commandText to be empty since it is in a using block.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的命令文本每次都是相同的。不要重建它。尝试一下:
由于很多原因,它更好:
Your command text is the same every time. Don't rebuild it. Try this:
It's better for a lot of reasons:
除了原始问题之外,以下几行不需要在循环中
您可以使用该字符串一次来创建带有参数化查询的命令,并在循环中使用相同的 objCommand 实例。唯一属于循环的就是动态值。
Other than the original question, the following lines need not be in the loop
You could use the string once to create a command with parameterized query and use the same
objCommand
instance in the loop. The only thing that belongs in the loop is the dynamic values.