从Checkboxlist在VB.net中创建SQL查询

时间:2014-04-04 17:57:16

标签: asp.net sql vb.net checkboxlist

我有一个checkboxlist,我从数据库中动态填充它。例如,在填充后,复选框列表就像:

  • 洛杉矶
  • 纽约
  • 伦敦
  • 柏林
  • 阿姆斯特丹

我想根据复选框创建一个SQL查询。如果我只想选择一个城市(例如只有纽约),我希望结果为:

  

(城市= 2)

这是正常的,但当我有多个城市(例如纽约,伦敦和阿姆斯特丹)时,我希望结果为例:

  

(城市= 2)或(城市= 3)或(城市= 5)

或者,如果我选择洛杉矶和柏林,我希望结果如下:

  

(城市= 1)或(城市= 4)

我怎样才能做到这一点?这是我的代码,但我已经堆叠了。有什么想法吗?

Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim var As String = ""
    Dim counter As Integer = 0
    Dim myList As New List(Of String)()
    For i As Integer = 0 To CheckBoxList1.Items.Count - 1
        If CheckBoxList1.Items(i).Selected Then
            myList.Add(i + 1)
            counter = counter + 1
            If counter = 1 Then
                var = "(City =" & i + 1 & ")"
            Else
                Console.WriteLine(myList(1))
                Dim myArray As String() = myList.ToArray()
                For j As Integer = 1 To myArray.Length
                    Dim var2 As String = " OR (City =" & counter & ")"
                    var = "(City =" & myArray(0) & ")" & var2
                Next
            End If
        End If
    Next
    SQL = "SELECT * FROM Data1 WHERE (" & var & ") ORDER BY [ID]"
    Session("Search") = SQL
    Server.Transfer("Data_Form.aspx")
End Sub

2 个答案:

答案 0 :(得分:2)

我最推荐的是查看表值参数:

  

http://msdn.microsoft.com/en-us/library/bb675163(v=vs.110).aspx

这将解决您的问题,并帮助您避免SQL注入漏洞。

但是如果你真的坚持使用字符串连接,请尝试使用IN()条件,最后你会得到更像CITY IN (1,2)而不是(City = 1 OR City = 2)的内容。您可以通过使用未使用的ID来更轻松地编写它,如下所示:

Dim cityClause As String = " CITY IN (-1{0})" 'start with a valid clause
Dim cityIDs As String = ""
For Each box As ListItem In CheckBoxList1.Items.Where(Function(b) b.Selected)
     'Try storing the ID for each city in the value part of each listitem,
     ' rather than using the index order 
     cityIDs = cityIDs & "," & box.Value
Next box
cityClause = string.Format(cityClause, cityIDs)

答案 1 :(得分:1)

您可以使用City IN(2,3,5)代替(City = 2) OR (City = 3) OR (City = 5)

Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim condition As String = ""
    For i As Integer = 0 To CheckBoxList1.Items.Count - 1
        If CheckBoxList1.Items(i).Selected Then
            condition = condition & "," & (i + 1)
        End If
    Next
    SQL = "SELECT * FROM Data1 WHERE (" & condition.SubString(1) & ") ORDER BY [ID]"
    Session("Search") = SQL
    Server.Transfer("Data_Form.aspx")
End Sub