所以我正在用Java编写一个小程序。基本上,我希望用户使用一个或1-3个搜索查询来搜索数据库,他们可以使用任何组合。
一个搜索查询示例是:图书名,ISBN,作者名称
用户可以使用任何组合进行搜索(仅按图书名称、或图书名称和作者名称或所有3种.)进行搜索。
基本上,我想编写一个主SQL语句(MYSQL),它将从数据库中提取结果。问题是,我不知道如何处理空白输入。
因此,假设用户输入:
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而不是"",那么查询仍然会失败。
这意味着它在数据库中找不到正确的书(即使是现在的),因为它仍然在列中寻找"“或null。
是否有任何方法像“幽灵”或不可见变量那样传递SQL查询,以使SQL查询像我所希望的那样工作?
还是我必须走很长的路,为每一个可能的组合做一个SQL查询?
发布于 2014-04-08 02:40:15
使用OR而不是AND
Change:
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 );
}现在,您可以执行该语句并获取结果集。
https://stackoverflow.com/questions/22925908
复制相似问题