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
I think, it is redundant.
rs.getObject("ID_PARENT")
should return anInteger
object ornull
, if the column value actually wasNULL
. So it should even be possible to do something like:The default for
ResultSet.getInt
when the field value isNULL
is to return0
, which is also the default value for youriVal
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:
(Edited as @martin comments below; the OP code as written would not compile because
iVal
is not initialised)Just check if the field is
null
or not usingResultSet#getObject()
. Substitute-1
with whatever null-case value you want.Or, if you can guarantee that you use the right DB column type so that
ResultSet#getObject()
really returns anInteger
(and thus notLong
,Short
orByte
), then you can also just typecast it to anInteger
.