Monday, January 16, 2012

Nice way to clean up JDBC resources in JDBC 4.1 (Java 7)

I was working on a small prototype of an application and had the luxury of working on top of Java 7. I was struck by how much boiler plate code we can avoid when working with JDBC.

Following is the code sample to read from a table using PreparedStatement.

try(
 Connection connection = ServiceLocator.getConnection;
 PreparedStatement stmnt = connection.prepareStatement(YOUR_SELECT_QUERY_HERE);
){
   stmnt.setString( 1, parameterValue1);
   stmnt.setString( 2, parameterValue2);


   ResultSet rs = stmnt.executeQuery();
   while(rs.next()){
   ......

   }
}


And this is it. No long, ugly and trite finally blocks to close connection, statements and resultsets.