Checking for a null int value from a Java ResultSet
Another solution:
public class DaoTools {
static public Integer getInteger(ResultSet rs, String strColName) throws SQLException {
int nValue = rs.getInt(strColName);
return rs.wasNull() ? null : nValue;
}
}
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)