Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking for a null int value from a Java ResultSet

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

like image 976
ian_scho Avatar asked May 27 '10 10:05

ian_scho


People also ask

How do you check for null in ResultSet?

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.

Can ResultSet be null?

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.


1 Answers

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)

like image 77
Richard Avatar answered Nov 15 '22 18:11

Richard