How to check if value from ResultSet returned NULL?

Fetching data from NULLABLE columns via JDBC might be tricky since java.sql.ResultSet returns primitive values. If such column contains NULL user will get default value ex. 0 for int. Ignoring this behaviour may lead to serious bugs.

Bellow example shows the problem:

// Assume that counter columnis NULL
int counter = resultSet.getInt("counter");

// If column value will return NULL counter will be set to 0
assertThat(counter).isEqual("0");

ResultSet.wasNull() method

To address this issue user should fetch the value and then call resultSet.wasNull() method. After this user may for example box the primitive to Integer and continue processing.

// Assume that counter column may contain null.
int counter = resultSet.getInt("counter");

// Check if last column read had value of SQL NULL
if (resultSet.wasNull() {
    return null;
} else {
    return Integer.of(counter);
}

Read more

  1. Javadoc ResultSet.getInt()
  2. Javadoc ResultSet.wasNull()