Java mySQL多个Where子句

时间:2017-04-26 14:51:33

标签: java mysql where

我有一个由"Title", "Genre", "Author" and "PageNumber"列组成的Book表我还有一个searchBook(String title, String author, String Genre)方法来搜索图书。我正在从用户检索这些参数,因此其中一个或多个可以为null但我仍然希望使用其余参数进行搜索。我可以写出所有可能的案例(例如if(title.equals("") && !author.equals("") && !genre.equals(""))但这对我来说似乎很愚蠢。有没有一个简短的方法可以做到这一点?

3 个答案:

答案 0 :(得分:0)

您可以将查询拆分为以下内容:

String query= "SELECT * FROM table WHERE 1=1 ";

if(!title.equals("")){

 query += " AND title=?";

}
if(!author.equals("")){

 query += " AND author=?";

}

依旧......

答案 1 :(得分:0)

如果你完全控制了这个,那么你不应该用null参数调用这个方法,而应该使用方法重载。您还可以使用自己的构建器或条件模式来构造仅具有非空值的查询。

您还可以构造一个在参数为空时选择所有内容的查询,例如:

SELECT * FROM Books WHERE title = IFNULL("something", title) AND author = IFNULL(null, author) AND genre = IFNULL(null, genre)

这意味着,如果您的参数为null,它将被替换为列的名称,从而选择所有内容,如果它不为空(如我的示例中的标题),则'只是要拿这个头衔。我没有提出这个解决方案,但表现不佳。

答案 2 :(得分:0)

以下是为?(因此为private void searchBook(final String title, final String author, final String Genre) { Map<String, String> validParams = new HashMap<String, String>(); if (!title.equals("")) { validParams.put("title", title); } if (!author.equals("")) { validParams.put("author", author); } if (!Genre.equals("")) { validParams.put("genre", Genre); } if(validParams.isEmpty()){ // if no value is correct, return return; } StringBuilder queryBuilder = new StringBuilder(); queryBuilder.append("SELECT name from BOOK "); boolean queryBuildStarted = false ; for(String key : validParams.keySet()){ if(!queryBuildStarted){ queryBuilder.append(" WHERE "); queryBuildStarted = true; } else{ queryBuilder.append(" AND "); } queryBuilder.append(key+" = ?"); } PreparedStatement statement = connection.prepareStatement(queryBuilder.toString()); int index = 1; for(String key : validParams.keySet()){ statement.setString(index, validParams.get(key)); index ++; } ResultSet rs = statement.executeQuery(); // do stuff } 占位符)构建查询的示例,仅针对可用值,然后继续替换值并执行查询:

import requests
from lxml import html

def Startpoint(mpage):
    leaf=1
    while leaf<=mpage:
        link="http://www.austrade.gov.au/"
        address = "http://www.austrade.gov.au/suppliersearch.aspx?smode=AND&ind=Agribusiness%7c%7cArts+%26+Recreation%7c%7cBuilding+%26+Construction%7c%7cBusiness+%26+Other+Services%7c%7cConsumer+Goods%2c+Non-Food%7c%7cDefence%2c+Security+%26+Safety%7c%7cEducation+%26+Training%7c%7cEnvironment+%26+Energy%7c%7cFinance+%26+Insurance%7c%7cFood+%26+Beverage%7c%7cGovernment%7c%7cHealth%2c+Biotechnology+%26+Wellbeing%7c%7cICT%7c%7cManufacturing+(Other)%7c%7cMining%7c%7cTourism+%26+Hospitality%7c%7cTransport&folderid=1736&pg=" + str(leaf)
        try : 
            page = requests.get(address, timeout=30)
        except requests.exceptions.ReadTimeout: 
            print('timed out')
            continue
        page = requests.get(address)
        tree = html.fromstring(page.text)
        titles=tree.xpath('//a[@class="Name"]')
        for title in titles:
            href = link + title.xpath('./@href')[0]
            Endpoint(href)
        leaf+=1

def Endpoint(address):
    try : 
        page = requests.get(address, timeout=30)
    except requests.exceptions.ReadTimeout: 
        print('timed out')
    else : 
        tree=html.fromstring(page.text)
        titles = tree.xpath('//div[@class="contact-details block dark"]')
        for title in titles:
            try :
                Name=title.xpath('.//p[1]/text()')[0] if len(title.xpath('.//p[1]/text()'))>0 else None
                Name1=title.xpath('.//p[3]/text()')[0] if len(title.xpath('.//p[3]/text()'))>0 else None
                Metco=(Name,Name1)
                print(Metco)
            except:
                continue

Startpoint(10)