Consider this simple method:
public ResultSet getByOwnerId(final Connection connection, final Integer id) throws SQLException { PreparedStatement statement = connection.prepareStatement("SELECT * FROM MyTable WHERE MyColumn = ?"); statement.setObject(1, id); return statement.executeQuery(); }
It is assumed that the sample method selects everything from the table where the column value corresponds, which should be simple. The ugly detail is that passing NULL for the identifier will result in an empty ResultSet, no matter how many rows there are in the database, since SQL defines NULL as not euqaling anyting, even NULL. The only way to select the lines that I know of is to use another where clause:
SELECT * FROM MyTable WHERE MyColumn IS NULL
Unfortunately, the only way to make the method work correctly in all cases, apparently, is to have two completely different execution patterns, one for the case when the id argument is null and the other for regular values.
This is very ugly, and when you have a few columns that can be reset, you can quickly become very dirty. How can I handle NULL and normal values using the same code / code statement?
source share