For example I have the following select query for a PreparedStatement:
"SELECT FOO FROM BAR WHERE FOOBAR=?"
The parameter for FOOBAR can have a value and it could also be null.
Would the following code work?
if(<condition>) preparedStatement.setString(1, "<string value>");
else preparedStatement.setString(1, null);
If not, how should this be handled?
The IS NULL condition is satisfied if the column contains a null value or if the expression cannot be evaluated because it contains one or more null values. If you use the IS NOT NULL operator, the condition is satisfied when the operand is column value that is not null, or an expression that does not evaluate to null.
A null value is a special value that Db2 interprets to mean that no data is present. If you do not specify otherwise,Db2 allows any column to contain null values. Users can create rows in the table without providing a value for the column. Using the NOT NULL clause enables you to disallow null values in the column.
Avoid using getXXX( ) methods that return primitive data types. Use wrapper classes for primitive data types, and use the ResultSet object's wasNull( ) method to test whether the wrapper class variable that received the value returned by the getXXX( ) method should be set to null.
By using the assignment operator (“=”), you can set any value of a column to NULL by using the Update Statement.
It won't work, null has no equivalence. If you're using a PreparedStatement, try this:
if(<condition>) preparedStatement.setObject(1, "<string value>");
else preparedStatement.setNull(1, Types.VARCHAR);
It will send the null as an IN parameter.
As per SQL standard, if a column has a NULL value, the search condition to check if it has NULL value is "column IS NULL". If column does not have null value you can have condition such as "column = 'blabla'. To make parameter markers work in both cases, change the statement as following:
SELECT FOO FROM BAR WHERE COALESCE(FOOBAR, 'a') = ? "
and have the following code:
if(<condition>) preparedStatement.setString(1, "<string value>");
else preparedStatement.setString(1, "a");
Whatever @Mark suggested did not work for me on Oracle.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With