2

In my java code i want to use a SELECT statement to retrieve an ID from a table. To do this, i use the prepareStatement java functionality.

PreparedStatement pst = con.prepareStatement(sql);
pst.setString(1, entry1);
pst.setString(2, entry2);
pst.setString(3, entry3);
ResultSet rs = pst.executeQuery();

entry1, entry2 and entry3 are variables. However some of these variables can be "null". So my sql statement then becomes:

SELECT ID FROM some_table WHERE col1="val1" AND col2="val2" AND col3=null;

This query will fail and so i have to change my query to this:

SELECT ID FROM some_table WHERE col1="val1" AND col2="val2" AND col3 IS NULL;

How do i do this? This is a small example and i have many tables and many columns that can sometimes have a null value. So to replace this part of the query would be the easiest option i can see. Can this be done or do i need to check all my variables before. many thanks!

Linda

2 Answers 2

2

String concatenation and ternary conditional operator.

String sql = "SELECT ID" +
              " FROM some_table" +
             " WHERE col1 " + (entry1 != null ? "= ?" : "IS NULL") +
               " AND col2 " + (entry2 != null ? "= ?" : "IS NULL") +
               " AND col3 " + (entry3 != null ? "= ?" : "IS NULL");
try (PreparedStatement pst = con.prepareStatement(sql)) {
    int paramIdx = 0;
    if (entry1 != null)
        pst.setString(++paramIdx, entry1);
    if (entry2 != null)
        pst.setString(++paramIdx, entry2);
    if (entry3 != null)
        pst.setString(++paramIdx, entry3);
    try (ResultSet rs = pst.executeQuery()) {
        ...
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2

You can also try the NULL-safe equal (IS DISTINCT FROM) operator <=>

SELECT ID FROM some_table WHERE col1 <=> ? AND col2 <=> ? AND col3 <=> ?;

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.