Handling
NULL Values:
SQL's use of NULL values and Java's use of null are
different concepts. So how do you handle SQL NULL values in Java? There are
three tactics you can use:
·
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.
·
Use primitive data types and the ResultSet
object's wasNull( ) method to test whether the primitive variable that received
the value returned by the getXXX( ) method should be set to an acceptable value
that you've chosen to represent a NULL.
Here is one example to handle a NULL value:
Statement stmt = conn.createStatement( );
String sql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);
int id = rs.getInt(1);
if( rs.wasNull( ) ) {
id = 0;
}