How do I get a Double out of a resultset instead of double?

Viewed 24512

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.

5 Answers

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.

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;
}

In kotlin:

private fun ResultSet.getDoubleOrNull(columnIndex: Int): Double? when {

     this.getObject(columnIndex) == null -> null

     else -> this.getDouble(columnIndex)

} 
Related