如何在 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)
最佳答案
将代码更改为参数化查询非常简单。但我会更改逻辑,以便在循环列表时集中创建参数。从方法返回后,这将避免第二次循环来构建参数
' pass also the connection and lets return a DbCommand filled with proper parameters'
Public Shared Function CreateInsertSqlCommand(ByVal DbConnection cn,
ByVal seminarId As Integer,
ByVal addBefugnisseList As List(Of Befugnisse)) As DbCommand
' Use a StringBuilder to get better memory footprint with repeated string changes'
Dim strIns As StringBuilder = new StringBuilder()
Dim command As DbCommand = Nothing
Dim insertQuery As String = "INSERT INTO teilnehmerkreiszuordnung(SeminarID,
befugnisID) VALUES "
If (addBefugnisseList.Any()) Then
'Create the command and add the invarian parameter'
command As DbCommand = cn.CreateCommand()
command.Parameters.Add("@s", MySqlDbType.Int32).Value = seminarID
' loop and add the list parameters while building the parameters placeholders'
For i = 0 To (addBefugnisseList.Count - 1)
strIns.AppendFormat($"(@s,@a{i}),")
command.Parameters.Add($"a{i}", MySqlDbType.Int32).Value = addBefugnisseList(i).AutoID
Next
' Remove the last comma'
if strIns.Length > 0 Then
strIns.Length = strIns.Length - 1
End If
command.CommandText = insertQuery + strIns.ToString()
End If
Return command
End Function
Using cn As DbConnection = DbConnection
Using command As DbCommand = Teilnehmerkreiszuordnung.CreateInsertSqlCommand(cn, id, addBefugnisseIdList)
if command IsNot Nothing Then
command.ExecuteNonQuery()
End If
End Using
End Using
关于mysql - 添加一对值作为 SQL 查询中的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57056815/