Reputation: 39
i'm making a Java program that contains a search engine feature to show the records from the database according to different criterias selected by the user out of comboboxes. I need to be able to modify the WHERE conditions of an SQL query according to what the user has selected. If he hasn't selected any value from the comboboxes then the default would be WHERE=1, if he has selected criteria from one combobox then override the variable so the 1 change it to WHERE state
=oklahoma
for example, and he selects 2 or more just keep concatenating them: WHERE state
=oklahoma
AND gender
=male
, and so on with as many comboboxes he sets.
i've tried to do this but i've read there are libraries that can make this easier but i don't know any, if this can be done with a library please name it and show the code to do it please
Upvotes: 1
Views: 189
Reputation: 2649
If the combo box number i
is selected then isSelected[i]=true
.
content[i]
is the value of the combo box number i
.
First Solution
PreparedStatement ps = (PreparedStatement) con.prepareStatement
(“SELECT username, password FROM users WHERE
state LIKE ? AND gender LIKE ?″); // AND ...
for(int i=0; i<n; i++) // n number of combo boxes
if (!isSelected[i])
ps.setString(i+1,"%");
else
ps.setString(i+1,content[i]);
ResultSet rs=ps.executeQuery();
Second solution
PreparedStatement ps = (PreparedStatement) con.prepareStatement
(“SELECT username, password FROM users WHERE (? OR
state=?) AND (? OR gender=?)″); // AND ...
for(int i=0; i<n; i++) {// n number of combo boxes
ps.setString(2*i+1,content[i]);
ps.setBoolean(2*i+2,isSelected[i]);
}
ResultSet rs=ps.executeQuery();
Upvotes: 3