Daily Archives: August 4, 2006

Why jdbc needs a special api to set nulls?

While Hibernate and other persistence frameworks are good, there are times why one wants to stick to the plain jdbc. One pain point with using jdbc is setting the parameters. People use various paradims including stmt.setInteger(i++,value); to keep track of the index. However, with JDK 1.5 supporting varargs, one can write a utility function like

public void update(PreparedStatement pstmt,Object ... vals) {

for(int i=0;i<i++) {
pstmt.setObject(i+1,vals[i]);
}
}

But if one of the values is a null, then the above doesn’t seem to work. One has to explicitly use stmt.setNull(index,type) api. Not sure why setting a bind to null requires specifying the data type.

Advertisements

Leave a comment

Filed under JDBC