0

I am creating a Java program that interfaces with a mysql database for a school project: I am using java mysql connector to execute the following query when the user hits the search button through a GUI:

public ResultSet getBooks(String book_id,String title,String author)
{
    ResultSet rs = null;
    try{
        Statement stmt = conn.createStatement();
        rs = stmt.executeQuery("SELECT book_id,title,author_name,branch_id,no_of_copies   FROM "
                + "(temp_author NATURAL JOIN book_copies) "
                + "WHERE book_id like '%"+book_id+"%' OR title like '%"+title+"%' OR author_name like '%"+author+"%';");

    }
    catch(SQLException ex) {
        System.out.println("Error in connection: " + ex.getMessage());
    }
    return rs;
}

The problem with this query is that if any of the fields (book ID , title or author) are empty, the query returns true as result. So my question is how do I use the wildcard to search for a matching string but return a null set when the strings (boook_id,title or author) are empty.

Thank you.

PS: I wasn't able to post an image of the GUI due to my low reputation.

Ajay Karthik
  • 45
  • 1
  • 2
  • 11

2 Answers2

1

Assuming your book_id String is not null, you could this:

WHERE ('"+book_id+"' <> '' AND book_id like '%"+book_id+"%') OR 
      ('"+title+"' <> '' AND title like '%"+title+"%') OR 
      ('"+author_name+"' <> '' AND author_name like '%"+author+"%')

I recommend you to use prepared statements also (for safety!).

Bart Friederichs
  • 33,050
  • 15
  • 95
  • 195
0

Just do something like this and include and statements with the rest of your arguments

If (isNull(title)&&isNull(author)&&isNull(book_id)) return null;
fclinton
  • 25
  • 7
  • I doubt they are `null`, as that would generate a runtime error in the string concatenation. You could would write `if ("".equals(title)) ...`. But that doesn't fix it, as this needs all of them to be not-empty, which is not the case. – Bart Friederichs Jul 06 '14 at 20:33
  • The strings aren't null, they could by empty of the form ("") or not empty – Ajay Karthik Jul 06 '14 at 20:37