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
Another solution:
Just an update with Java Generics.
You could create an utility method to retrieve an optional value of any Java type from a given ResultSet, previously casted.
Unfortunately, getObject(columnName, Class) does not return null, but the default value for given Java type, so 2 calls are required
In this example, your code could look like below:
Happy to get feedback
Another nice way of checking, if you have control the SQL, is to add a default value in the query itself for your int column. Then just check for that value.
e.g for an Oracle database, use NVL
then check
Of course this also is under the assumption that there is a value that wouldn't normally be found in the column.
For convenience, you can create a wrapper class around ResultSet that returns null values when
ResultSet
ordinarily would not.AFAIK you can simply use
even if it is NULL.
With java 8 you can do this:
In that case you ensure that the nVal will be null (and not zero) if the SQL value is NULL