tags:

views:

266

answers:

4

When working with a JDBC resultset I want to get Double instead of double since this column is nullable. Rs.getDouble returns 0.0 when the column is null.

+8  A: 

You can check for wasNull on your ResultSet to find out if the value was null.

Note that you must first call one of the getter methods on a column to try to read its value and then call the method wasNull to see if the value read was SQL NULL.

If you really need a Double afterwards, you can create it from the double returned.

Peter Lang
+1 hardly more to say
stacker
+3  A: 

Use ResultSet.wasNull -> http://java.sun.com/javase/6/docs/api/java/sql/ResultSet.html#wasNull%28%29

Basically it works for all primitive types, you first use getDouble, getInt, etc., and then only if the result is 0 you use wasNull.

Yoni
+3  A: 

An alternative to the aforementioned ResultSet#wasNull() is to test ResultSet#getObject() on null so that you can nicely put it in a single line in combination with the ternary operator:

Double d = resultSet.getObject("column") != null ? resultSet.getDouble("column") : null;

instead of

Double d = resultSet.getDouble("column");
if (resultSet.wasNull()) {
    d = null;
}
BalusC
Interesting point, although there is a performance penalty here for calling a getter twice in the common case when the value is not null. Maybe it is possible just to cast the result of getObject to a Double?
Yoni
@Yoni: There's certainly no performance penalty in invoking a simple getter. The data is *already* there since `next()` has been called.
BalusC
but also note what the documentation of ResultSet says: `For maximum portability, result set columns within each row should be read in left-to-right order, and each column should be read only once.` :-@
Carlos Heuberger
@Carlos: that was specified over 15 years ago. This is really not an issue nowadays.
BalusC
+1  A: 

You could just do:

Double d = (Double) resultSet.getObject("column");

then you don't have to worry if it was null.

MRhodes