So, I have 4 menu selections (product, location, course type and category), all of which can be null (programmed using JSF, but that doesnβt matter for this question, since this is an SQL question).
Selecting the menu will send the bean-driven variable that the user selected, and using the prepared search operator in the database table, using the information from the menu that the user selected (if any).
If the user leaves the null menu item, he should look for everything.
If the user leaves 1 or 2 or 3 menu items with information and the other zero, he should search accordingly.
My problem is how can I do this without a bunch of if / then statements in the bean attached to the corresponding sql statement for each?
Or is there one better sql statement that I can do to do all this?
I use a prepared statement in Java.
I tried this:
if (product != null && location != null && courseType != null && category != null) { pstmt = conn.prepareStatement("select * FROM Courses WHERE " + "product = ? " + "and location = ? " + "and courseType = ? " + "and category = ?"); pstmt.setString(1, product); pstmt.setString(2, location); pstmt.setString(3, courseType); pstmt.setString(4, category); } else if (product == null && location != null && courseType != null && category != null) { pstmt = conn.prepareStatement("select * FROM Courses WHERE " + "location = ? " + "and courseType = ? " + "and category = ?"); pstmt.setString(1, location); pstmt.setString(2, courseType); pstmt.setString(3, category); }
etc., but I would have to do it as 16 times for each case 1, which is zero, and not others? There should be a smarter way (either using 1 sql statement, or just a few java if / then statements?)
UPDATE thanks to Luigi Mendoza! My code works as follows:
pstmt = conn.prepareStatement("select * FROM Courses WHERE " + "(product = ? or ? is null) " + "and (location = ? or ? is null) " + "and (courseType = ? or ? is null)" + "and (category = ? or ? is null)"); pstmt.setString(1, product); pstmt.setString(2, product); pstmt.setString(3, location); pstmt.setString(4, location); pstmt.setString(5, courseType); pstmt.setString(6, courseType); pstmt.setString(7, category); pstmt.setString(8, category); rset = pstmt.executeQuery();
Update yes, I had to use = "" instead of null for another mysql database (maybe different versions or something else)