In Java I'm trying to test for a null value, from a ResultSet, where the column is being cast to a primitive int type.
int iVal; ResultSet rs = magicallyAppearingStmt.executeQuery(query); if (rs.next()) { if (rs.getObject("ID_PARENT") != null && !rs.wasNull()) { iVal = rs.getInt("ID_PARENT"); } }
From the code fragment above, is there a better way to do this, and I assume that the second wasNull() test is redundant?
Educate us, and Thanks
The wasNull() method of the ResultSet interface determines whether the last column read had a Null value. i.e. whenever you read the contents of a column of the ResultSet using the getter methods (getInt(), getString etc...) you can determine whether it (column) contains null values, using the wasNull() method.
No matter how many rows are returned(starting from 0), the resultSet will never be null. The only case in which a resultset will remain null is when an exception is thrown... but the program flow will jump to the Exception handling block anyways.
The default for ResultSet.getInt
when the field value is NULL
is to return 0
, which is also the default value for your iVal
declaration. In which case your test is completely redundant.
If you actually want to do something different if the field value is NULL, I suggest:
int iVal = 0; ResultSet rs = magicallyAppearingStmt.executeQuery(query); if (rs.next()) { iVal = rs.getInt("ID_PARENT"); if (rs.wasNull()) { // handle NULL field value } }
(Edited as @martin comments below; the OP code as written would not compile because iVal
is not initialised)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With