Getting Integer object from ResultSet [duplicate]

Just check if the field is null or not using ResultSet#getObject().

Integer foo = resultSet.getObject("foo") != null ? resultSet.getInt("foo") : null;

Or, if you can guarantee that you use the right DB column type so that ResultSet#getObject() really returns an Integer (and thus not Long, Short or Byte), then you can also just typecast it.

Integer foo = (Integer) resultSet.getObject("foo");

UPDATE: For Java 1.7+

Integer foo = resultSet.getObject("foo", Integer.class);

You can check for wasNull after retrieving the value.

From the documentation:

Reports whether the last column read had a value of SQL NULL.
Note that you must first call one of the getter methods on a column to try to read its value and then call the method wasNull to see if the value read was SQL NULL.


There is a simpler way., Just type cast it. If null, it will be null. If valid, then it becomes the autoboxed object.

(Integer) resultSet.getObject("foo")