在mySQL&中构造像查询一样VB.Net

时间:2016-07-01 03:55:33

标签: mysql asp.net vb.net listview

我有ListView&多个过滤器作为checkboxList。一切正常,但喜欢条款不正确。它就像下面的

select * from products where  category Like '% Apparels, Bluetooth%'

但它应该是这样的

select * from products where  category Like '% Apparels%' or category Like '%Bluetooth%'

如何更改代码以正确构建查询?

Public Function buildWhereClause() As String
        Dim constr As String = ConfigurationManager.ConnectionStrings("conio").ConnectionString
        Dim query As String = "select * from products"
        Dim joiner As String = " "
    Dim condition As String = String.Empty
    Dim priceCondition As String = String.Empty

    For i = 0 To priceFilter.Items.Count - 1
        If priceFilter.Items(i).Selected Then
            Dim price As String = priceFilter.Items(i).ToString
            priceCondition = String.Concat(priceCondition, joiner, String.Format("'{0}'", price))
            If joiner = " " Then joiner = ", "
        End If
    Next

    Dim categoryCondition As String = String.Empty
    joiner = " "

    For i = 0 To categoryFilter.Items.Count - 1
        If categoryFilter.Items(i).Selected Then
            Dim category As String = categoryFilter.Items(i).ToString
            categoryCondition = String.Concat(categoryCondition, joiner, String.Format("{0}", category))
            If joiner = " " Then joiner = ", "
        End If
    Next

    Dim whereClause As String = String.Empty
    joiner = " where "
    If Not String.IsNullOrEmpty(priceCondition) Then
        whereClause = String.Concat(whereClause, joiner, String.Format(" price_range IN ({0})", priceCondition)) ' and sub_category IN ({0})", condition.Substring(0, condition.Length - 1))
        joiner = " and "
    End If

    If Not String.IsNullOrEmpty(categoryCondition) Then
        whereClause = String.Concat(whereClause, joiner, String.Format(" category Like '%{0}%'", categoryCondition))
        joiner = " and "
    End If

    'If Not String.IsNullOrEmpty(brandCondition) Then
    '    whereClause = String.Concat(whereClause, joiner, String.Format(" sub_category in ({0})", categoryCondition))
    '    joiner = " and "
    'End If

    Dim masterClause As String = String.Empty
    masterClause = (query & whereClause)
End Sub

1 个答案:

答案 0 :(得分:1)

所以你通过循环categoryCondition="Apparels, Bluetooth"得到categoryFilter.Items这里你可以做的是用,替换%' or category Like '%然后每件事都会很酷。请考虑以下事项:

If Not String.IsNullOrEmpty(categoryCondition) Then
    whereClause = String.Concat(whereClause, joiner, String.Format("category Like '%{0}%'", categoryCondition.Replace(",","%' or category Like '%"))       
End If