Multiselect month from table - sqlite
I get 1-n selected months from a JList. Now I'd like to select rows from a sqlite DB with the selected months.
Is there a way to do it the easy way to build the select string, e.g. with a loop and a LIKE statement?
resultSet = statement
.executeQuery("SELECT sum(Betrag) FROM record WHERE strftime('%Y',Datum)='"
+ options.getList_years().get(options.getCurrent_year_index())
+ "' AND strftime('%m',Datum) LIKE '"
+ "02 || 04 || 12" //Here are the months,
+ "' AND Sektion LIKE '"
+ "%"
+ "' AND Inhaber LIKE '"
+ list_accounts.getSelectedVa开发者_开发百科lue()
+ "' AND Ausgabe='"
+ "true';");
Or has it to look that way?
strftime('%m',Datum)='02' OR strftime('%m',Datum)='04' OR trftime('%m',Datum)='12'
You should use an IN clause:
... AND strftime('%m',Datum) IN ('02', '04', '12')
But you should definitely not use string concatenation to set parameters dynamically in your query. This is the best way to suffer from SQL injection attacks. Use prepared statements, with a ?
placeholder for each of your parameter:
SELECT sum(Betrag) FROM record WHERE strftime('%Y',Datum) = ? ...
Learn more about prepared statements in the JDBC tutorial.
You will indeed have to use some loop or utility to build the IN clause. StringUtils
from commons-lang is useful here:
"... AND strftime('%m',Datum) IN (" + StringUtils.repeat("?", ", ", months.size())
精彩评论