Wednesday
Nov172004
JDBC Annoyance
Wednesday, November 17, 2004 at 2:11PM
I like JDBC more than even DBI, which has always been my favorite database abstraction doodad. But this irritates the crap out of me. setLong()! Consider the following:
That works great, as long as someVar is a
So you could fix that with:
But that's so wordy! As I wrote this I decided that maybe this code would work:
It should handle the null. Let's hope so!
Connection conn = ...
PreparedStatement ps = conn.prepareStatement("SELECT name FROM customers WHERE customerid=?");
ps.setLong(1, someVar);
That works great, as long as someVar is a
long and not a Long. If someVar is a Long you have to call longValue() on your Long since setLong()'s signature is (int, long). But what if someVar is null? NPE!So you could fix that with:
if(someVar != null) {
ps.setLong(1, someVar);
} else {
ps.setNull(2, Types.INTEGER);
}
But that's so wordy! As I wrote this I decided that maybe this code would work:
ps.setObject(1, someVar, Types.INTEGER);
It should handle the null. Let's hope so!

Reader Comments