Checking for a Null Int Value from a Java Resultset

Checking for a null int value from a Java ResultSet

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)

JAVA - Checking for NULL value from a result set

Your probably could try using of ResultSet.getObject(int columnIndex) method. From its JavaDoc description:

This method will return the value of the given column as a Java
object. The type of the Java object will be the default Java object
type corresponding to the column's SQL type, following the mapping for
built-in types specified in the JDBC specification. If the value is an
SQL NULL, the driver returns a Java null.



Related Topics



Leave a reply



Submit