Use wasNull( ) Checks
SQL
NULL is a very useful tool that, unfortunately, is
frequently abused. A good database application uses
NULL in situations in which a row lacks a value.
For example, if you have an application in which one of the
attributes of the
Person table is
numPets, you should use NULL to
indicate that you do not know how many pets they have. Without
NULL, you would have to use a bogus value such as
-1.
Your JDBC code should always be checking for possible
NULL values from nullable columns using the
wasNull( ) method in ResultSet.
The actual value that JDBC returns for NULL values
in getter methods is undefined. Your code to check the number of
pets, for example, should look like the following fragment:
conn = ds.getConnection( );
stmt = conn.prepareStatement("SELECT numPets FROM Person WHERE personID = ?");
stmt.setLong(1, 13933L);
rs = stmt.executeQuery( );
if( rs.next( ) ) {
pets = rs.getInt(1);
if( rs.wasNull( ) ) {
pets = -1; // Java has no concept of null for numerics!
}
}