Question
How can I efficiently check for null integer values in a Java ResultSet?
int iVal;
ResultSet rs = magicallyAppearingStmt.executeQuery(query);
if (rs.next()) {
if (rs.getObject("ID_PARENT") != null && !rs.wasNull()) {
iVal = rs.getInt("ID_PARENT");
}
}
Answer
Handling null values retrieved from a database is crucial when working with Java's ResultSet. Primitives like int cannot take null values, so we must ensure that we correctly check for nulls before assignment to avoid errors.
Integer iVal;
ResultSet rs = magicallyAppearingStmt.executeQuery(query);
if (rs.next()) {
iVal = rs.getObject("ID_PARENT") != null ? rs.getInt("ID_PARENT") : null;
}
Causes
- Using primitive types directly can lead to NullPointerExceptions if the database field is null.
- Not checking the ResultSet for null values properly can cause runtime errors.
Solutions
- Use Integer instead of int to allow for nullability: `Integer iVal;`
- Check for null using `ResultSet` methods designed specifically for this purpose.
Common Mistakes
Mistake: Assigning a ResultSet value directly to a primitive type without checking for null.
Solution: Always use wrapper classes like Integer for nullable database fields.
Mistake: Assuming that `wasNull()` means the object was not null.
Solution: `wasNull()` returns true if the last value read was SQL NULL, so use it immediately after getting the value.
Helpers
- Java ResultSet
- null integer values
- check for null in ResultSet
- Java database programming
- ResultSet best practices