How to check if a double is null?

前端 未结 6 1175
天涯浪人
天涯浪人 2020-12-01 13:58

I\'m querying a database and some of the results I\'m getting are null. I\'m setting these values to a variable with a datatype of double. Let\'s call the variable \"results

6条回答
  •  孤街浪徒
    2020-12-01 14:20

    Firstly, a Java double cannot be null, and cannot be compared with a Java null. (The double type is a primitive (non-reference) type and primitive types cannot be null.)

    Next, if you call ResultSet.getDouble(...), that returns a double not a Double, the documented behaviour is that a NULL (from the database) will be returned as zero. (See javadoc linked above.) That is no help if zero is a legitimate value for that column.

    So your options are:

    • use ResultSet.wasNull() to test for a (database) NULL ... immediately after the getDouble(...) call, or

    • use ResultSet.getObject(...), and type cast the result to Double.

    The getObject method will deliver the value as a Double (assuming that the column type is double), and is documented to return null for a NULL. (For more information, this page documents the default mappings of SQL types to Java types, and therefore what actual type you should expect getObject to deliver.)

提交回复
热议问题