簡體   English   中英

在MYSQL查詢中傳遞空白/非空VARIABLE(使用Java)

[英]Passing a blank / non-null VARIABLE in MYSQL Query (using Java)

所以我正在用Java開發一個小程序。 基本上,我希望用戶使用一個或1-3個搜索查詢來搜索數據庫,並且他們可以使用任何組合。

搜索查詢示例為:書名,ISBN,作者名

用戶可以使用任何組合進行搜索(僅按書名搜索,或按書名和作者名搜索,或全部按3等...)。

我基本上想編寫一個主SQL語句(MYSQL),它將從數據庫中提取結果。 問題是,我不知道如何處理空白輸入

假設用戶輸入:

  • 書名=哈利·波特與密室

  • ISBN = <<留空>>

  • 作者名稱= JK羅琳

SQL查詢示例為:

SELECT *
FROM booklist
WHERE book_name = "Harry Potter and the Chamber of Secrets"
AND ISBN = ""
AND Author = "JK Rowling"; 

在Java代碼中,我使用PreparedStatement ,字符串為:

String temp =  " SELECT * " + 
               " FROM booklist " + 
               " WHERE Title = " + title + 
               " AND Author = \"" + author + "\"" + 
               " AND ISBN = \"" + isbn + "\""; 

由於用戶未輸入ISBN,因此SQL查詢失敗(因此代碼失敗)。 如果我使用null而不是“” ,則查詢仍將失敗。

失敗表示它不會在數據庫中找到正確的書(即使它存在),因為它仍在列中尋找“”或空值。

有什么方法可以傳遞類似“ ghost”或不可見變量的形式來使SQL查詢像我打算的那樣工作?

還是我必須走很長一段路才能對每種可能的組合進行SQL查詢?

使用OR代替AND

變更

String temp =  " SELECT * " + 
               " FROM booklist " + 
               " WHERE Title = " + title + 
               " AND Author = \"" + author + "\"" + 
               " AND ISBN = \"" + isbn + "\""; 

String temp =  " SELECT * FROM booklist " + 
               " WHERE Title = ? OR Author = ?" + 
               " OR ISBN = ?"; 

然后為准備好的語句設置參數。

pst.setString( 1, title );  
pst.setString( 2, author );
pst.setString( 3, isbn );

如果找到任何匹配的記錄,則使用OR ,然后將其提取。

而且,如果您仍想使用AND進行比較,並且不希望包含空輸入,則必須在JAVA動態准備語句。

StringBuilder sql = new StringBuilder( 1024 );
sql.append( " SELECT * FROM booklist " );
String whereCondition = "";
if( title != null && title.trim().length() > 0 ) {
    whereCondition += " title = ?";
}
if( isbn != null && isbn.trim().length() > 0 ) {
    whereCondition += (whereCondition.length() > 0 ? " AND " : "" );
    whereCondition += " isbn = ?";
}
if( author != null && author.trim().length() > 0 ) {
    whereCondition += (whereCondition.length() > 0 ? " AND " : "" );
    whereCondition += " author = ?";
}

sql.append( " where " ).append( whereCondition );
pst = con.prepareStatement( sql.toString() );

現在設置准備的參數,如下所示:
然后為准備好的語句設置參數。

int paramIndex = 1;

if( title != null && title.trim().length() > 0 ) {
    pst.setString( paramIndex++, title );  
}
if( isbn != null && isbn.trim().length() > 0 ) {
    pst.setString( paramIndex++, isbn );  
}
if( author != null && author.trim().length() > 0 ) {
    pst.setString( paramIndex++, author );  
}

現在,您可以執行該語句並獲取結果集。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM