47

A ResultSet provides method getInt() that returns primitive int. Is it possible to obtain the Integer object, which permits null? The DB field I'm retrieving is nullable and getInt() returns me 0 whenever the field is null.

Thanks

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Will Sumekar
  • 1,249
  • 5
  • 16
  • 25

3 Answers3

65

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);
kantianethics
  • 671
  • 5
  • 21
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • It should be inefficient either, since references to Boolean are cached as long as the constructor isn't used (Boolean.TRUE and FALSE). – Chris Dennett May 04 '11 at 10:32
  • Thanks. Unfortunately it adds boilerplate code. Wish there's a cleaner way. – Will Sumekar May 04 '11 at 10:36
  • 3
    What about `Integer foo = (Integer) rs.getObject("foo");`? (or use a try-catch to catch the casting error and set it to null/report error as needed). – ADTC Aug 02 '13 at 11:20
  • 1
    That would only work if the DB column type is mapped to Java `Integer`. See updated answer. – BalusC Jul 28 '14 at 10:21
  • 2
    Be careful with your driver and database. Unfortunately `resultSet.getObject("foo", Integer.class)` returned 0 for me when column was null. `(Integer) resultSet.getObject("foo")` returns null. I've used Oracle driver. – Tomasz Kalkosiński Sep 30 '19 at 14:26
12

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.

Peter Lang
  • 54,264
  • 27
  • 148
  • 161
8

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")
Sairam Krish
  • 10,158
  • 3
  • 55
  • 67