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

后端 未结 5 1806
南方客
南方客 2020-12-05 23:06

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 doi

相关标签:
5条回答
  • 2020-12-05 23:14

    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.

    0 讨论(0)
  • 2020-12-05 23:19

    Depending on your JDBC driver and database, you may be able to use a boxed type and cast:

    Double doubleValueOrNull = (Double)rs.getObject(1); // or .getObject("columnName")
    

    It will be null if the column was NULL.

    Be careful to check this still works if you change database.

    0 讨论(0)
  • 2020-12-05 23:19

    Use:

    rs.getObject(1)==null?null:rs.getBigDecimal(1).doubleValue()
    
    0 讨论(0)
  • 2020-12-05 23:34

    Or with java 8 you can do this:

    Double dVal = Optional.ofNullable(resultSet.getBigDecimal("col_name"))
                    .map(BigDecimal::doubleValue).orElse(null));
    
    0 讨论(0)
  • 2020-12-05 23:37

    Kotlin version to retrieve a nullable field:

    val parentId = resultSet.getObject("parent_id") as Double?
    
    0 讨论(0)
提交回复
热议问题