JDBC : getShort returns 0 on NULL

by bitznbitez

When using JDBC and the integerish data types of short, integer, long etc. be very very careful if you have nullable columns.   A very similar code segment to the following was found yesterday to be replacing nulls with 0’s in the target database.   This is part of a code segment that is reading from one database and inserting into another.

insArchiveOutput.setShort (15, rsOutput.getShort("some_column_name"));

The problem is that the machine numerics seem to consistently return 0 instead of null, requiring you to invoke rs.wasNull() to see if you really were supposed to have a null instead of a 0.   Its works out to be far less elegant than the above line of code, but it doesn’t mangle the data.

I would think this would be better known but this code snipped had slipped past multiple java programmers in a walkthrough and no one raised the possibility.