【发布时间】:2019-07-16 12:01:59
【问题描述】:
如何在 SQL 查询中添加一对值作为参数?
Dim insertQuery As String = Teilnehmerkreiszuordnung.CreateInsertSqlStatement(id, addBefugnisseIdList)
Using cn As DbConnection = DbConnection
Using command As DbCommand = cn.CreateCommand()
command.CommandText = insertQuery
// Add values with parameters???
command.ExecuteNonQuery()
End Using
End Using
CreateInsertSqlStatement 函数:
Public Shared Function CreateInsertSqlStatement(ByVal seminarId As Integer, ByVal addBefugnisseList As List(Of Befugnisse)) As String
Dim strIns = String.Empty
Dim insertQuery As String = String.Empty
If (addBefugnisseList.Any()) Then
For i = 0 To (addBefugnisseList.Count - 1)
strIns = strIns + String.Format("({0},{1})", seminarId, addBefugnisseList(i).AutoID)
If (addBefugnisseList.Count - 1 - i > 0) Then
strIns = strIns + ","
End If
Next
insertQuery = String.Format("INSERT INTO teilnehmerkreiszuordnung(SeminarID, befugnisID) VALUES {0}", strIns)
End If
Return insertQuery
End Function
函数的输出如下:
INSERT INTO teilnehmerkreiszuordnung(SeminarID, befugnisID) VALUES (2,5),(2,6),(2,7)
【问题讨论】:
-
您能解释一下您期望的查询文本是什么吗?或者您只是想问如何用参数化查询替换您当前的字符串连接方法?
-
如果我理解,你必须使用参数并做 3 次插入。
-
如果
addBefugnisseIdList包含要使用的值,那么对CreateInsertSqlStatement的调用已经返回一个预填充的查询字符串。只需执行它。但我建议你去准备一份声明来满足标准。 -
我希望查询文本是“INSERT INTO teilnehmerkreiszuordnung(SeminarID, befugnisID) VALUES (@s2, @b5),(@s2, @b6),(@s2,@b7)"
-
我会把逻辑改成这个。我会将 CreateInsertSqlStatement 更改为 CreateInsertSqlCommand 并让它在遍历列表时创建 DbCommand 和参数。如果需要,调用者只需调用 ExecuteNonQuery 或修复命令中的某些内容