Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Integer object from ResultSet [duplicate]

Tags:

java

jdbc

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

like image 534
Will Sumekar Avatar asked May 04 '11 10:05

Will Sumekar


1 Answers

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); 
like image 185
BalusC Avatar answered Oct 19 '22 10:10

BalusC