2

If I have a search module which has the following: search box, dropdown 1, dropdown 2.

And I have a query like this:

SELECT * FROM MY_TABLE where q1 = 'searchBox' AND q2 = 'dropdown1' AND q3 = 'dropdown2'

How can I make that query dynamic depending on user filter, so if the user only fills the search box, the query will be:

SELECT * FROM MY_TABLE where q1 = 'searchBox'

If the user fills search box and dropdown1, the query will be:

SELECT * FROM MY_TABLE where q1 = 'searchBox' AND q2 = 'dropdown1'

and if the user doesn't fill anything, the query will be:

SELECT * FROM MY_TABLE

I am using Java.

2
  • What RDBMS are you using? Commented Apr 17, 2016 at 15:44
  • I use mysql and java for my programming languange Commented Apr 17, 2016 at 15:45

2 Answers 2

4

There are frameworks that can help with this:

If you'd like to create a quick and simple solution, you can do something like the following:

List<String> params = new ArrayList<>();
StringBuilder sb = new StringBuilder();
sb.append("SELECT * FROM MY_TABLE WHERE 1 = 1");

if (searchBox != null) {
    sb.append(" AND q1 = ?");
    params.add(searchBox);
}

if (dropdown1 != null) {
    sb.append(" AND q2 = ?");
    params.add(dropdown1);
}

if (dropdown2 != null) {
    sb.append(" AND q3 = ?");
    params.add(dropdown2);
}

PreparedStatement preparedStatement = connection.prepareStatement(sb.toString());
for (int i = 1; i <= params.size(); i++) {
    preparedStatement.setString(i, params.get(i));
}

ResultSet resultSet = preparedStatement.executeQuery();
Sign up to request clarification or add additional context in comments.

Comments

0

To improve upon the code provided by @blacktide

PreparedStatement preparedStatement = connection.prepareStatement(sb.toString());
for (int i = 1; i <= params.size(); i++) {
    preparedStatement.setString(i, params.get(i));
}

You would instead want the line within the for loop to be

preparedStatement.setString(i, params.get(i-1));

Since arrays start at 0, we'd want to grab that zeroth index to set the first value added to the list to the first value to be updated in the SQL string. Otherwise you would grab the second value within params which would not be the intended value.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.