How do I in JDBC read a possibly null double value from resultSet?

double, java, jdbc, null

Solution

Option 1 is closest:

double d = rs.getDouble(1);
if (rs.wasNull()) {
  // do something
} else {
  // use d
}

It's not very nice, but that's JDBC. If the column was null, the double value is considered "bad", so you should check using `wasNull()` every time you read a primitive that is nullable in the database.

Problem

I have a column in my database that is typed `double` and I want to read the value from it using a JDBC ResultSet, but it may be null. What is the best way of doing this? I can think of three options none of which seem very good. Option 1: Bad because exception handling verbose and smelly ``` double d; try { d = rs.getDouble(1); // do something } catch(SQLException ex) { if(rs.wasNull()) { // do something else } else { throw ex; } } ``` Option 2: Bad because two fetches ``` s = rs.getString(1); // or getObject() if(s == null) { // do something else } else { double d = rs.getDouble(1); // do something } ``` Option 3: Bad because Java rather than SQL conversion ``` s = rs.getString(1); // or getObject() if(s == null) { // do something else } else { double d = Double.parseDouble(s); // do something } ``` Any suggestions on which way is better, or is there another superior way? And please don't say "Use Hibernate", I'm restricted to JDBC code only here.

Original source