I am creating a small web based tool that allows users to query a large lookup table in various ways. Since its a small tool, I’m using JSP/Servlets.
The lookup table has a definition something like this:
column1 | column2 | column3 | date | user | count
The user can query by column values or a range. Also, the results can be sorted by a specific column. Because the table has several hundred thousand of records, and growing rapidly, I’m using Oracle’s ROWNUM and only returning a small subset of results.
I have a form page that gets the search criteria from the user. I generate my query based on a series of conditions, for example:
query = "SELECT * FROM mytable WHERE 1=1 "
if(searchCriteria1 != "")
query += "AND column1='searchCriteria1' "
if(searchCriteria2 != "")
query += "AND column2='searchCriteria2' "
if(searchCriteria2 != "")
query += "AND column2='searchCriteria2' "
if(searchCriteria3 != "")
query += "AND column3='searchCriteria3' "
if((searchCriteria4 != "") && (searchCriteria5 != ""))
query += "AND date>='searchCriteria4' AND date<='searchCriteria5' "
etc...
(This is just simplified pseudo code)
The sorting is handled after the first results page is displayed. The user clicks on the column header of that page to sort by that column. This would be doing a post back and querying the database. Basically, I run the same code above but with this at the end:
if(sortColumn1)
query += "ORDER BY column1"
if(sortColumn2)
query += "ORDER BY column2"
if(sortColumn3)
query += "ORDER BY column3"
So, as you might imagine, my query building code is very long with all these different conditions. Any suggestions on a better way to do this?
String concatenation is not the best choice for SQL. The best you can do is to use QueryDSL or JOOQ and do it in the OO way. I am more familiar with QueryDSL. Look at the examples here.
As for SQL injection query engine will wrap your arguments in named parameters while constructing SQL.