嘿,我需要一些关于如何进行以下操作的想法:
我有一个文本框,用户可以键入ID以在数据库中搜索。它目前只检查1个ID。
示例:
User types in ID 645378
查询看起来像:
SELECT * FROM blahTable WHERE theID = '645378';
现在,我希望允许用户一次输入1个以上的ID并显示这些结果。
所以再一个例子是:
User types in ID(s): 645378, 78664, 901524
现在这就是我的问题发挥作用的地方。如何根据用户输入文本框的ID数创建查询?
任何帮助都会很棒!
大卫
答案 0 :(得分:4)
您可以在SQL中使用IN语句。
SELECT * FROM blahTable where theID in ('123','456','789')
我建议通过参数化查询来实现它,以避免Bobby Tables(SQL注入)
答案 1 :(得分:2)
只需使用IN
:
SELECT * FROM blahTable WHERE theID IN (645378, 78664, 901524);
请注意,如果您的值是实际字符串而不是数字,则需要一些额外的工作:
Dim asValues As String()
Dim sbQuery As New System.Text.StringBuilder(5000)
' Get the text, but remove any embedded semi-colons and single quotes for sql injection'
asValues = Miles.Text.Replace(";", " ").Replace("'", " ").Split(New Char() {","c}, StringSplitOptions.RemoveEmptyEntries)
sbQuery.Append("SELECT * FROM blahTable WHERE theID IN (")
Dim fUseComma As Boolean
' Add each value to the query string. In this case, we are wrapping with '
For Each sValue As String In asValues
' Test the value for reasonableness (example only)'
If IsNumeric(sValue) Then
' Only use the comma starting from the second valid item added
If fUseComma Then
sbQuery.Append(",")
Else
fUseComma = True
End If
sbQuery.Append("'").Append(CInt(sValue)).Append("'")
End If
Next
sbQuery.Append(")")
cmd.CommandText = sbQuery.ToString
答案 2 :(得分:1)
尝试这件事。
Dim xIDList As String = "645378, 78664, 901524" 'the user should separate ID by COMMA
Dim xID() As String = xIDList.Split(CChar(",")) 'splits the xIDlist
Dim xIDforQuery As String = String.Empty
For Each oID As String In xID
If oID.Trim.Length <> 0 Then
xIDforQuery &= "," & " '" & oID & "'" ' if ID is not numeric
' xIDforQuery &= "," & oID.ToString ' use this line if ID is numeric
End If
Next
xIDforQuery = xIDforQuery.Trim
xIDforQuery = CStr(IIf(Mid(xIDforQuery, 1, 1) = ",", Mid(xIDforQuery, 2, xIDforQuery.Length - 1), xIDforQuery))
Dim xFinalQuery As String = String.Empty
xFinalQuery = String.Format("SELECT * FROM blahTable where theID in ({0})", xIDforQuery)
' xFinalQuery is the final query statement but this approach is vulberable to SQL Injection.
答案 3 :(得分:0)
用户如何知道他们想要哪个ID?如果没有太多ID,使用多选列表框将改善UI并简化代码。如果有太多,则可以考虑使用自动完成文本框供用户选择可以从列表框中复制(删除)的项目以供查询使用。