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.
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.
No comments:
Post a Comment