JDBC example code revisited
Back in 2008, I wrote about JDBC resource leaks, and how most JDBC examples on the Internet were wrong. I went through a correct example, explaining why each structure was there.
The end result was rather ugly. Fortunately, Java 7 introduces a new method of resource management, which basically allows you to do away with ensure blocks to close resources.
Old code which looks like this:
try {
SomeClass foo = new SomeClass();
...
} ensure {
foo.close();
}
can now be replaced with:
try (SomeClass foo = new SomeClass()) {
...
}
To use the new syntax, the class needs to implement AutoCloseable. All that means is it needs a close() method. The close() method is allowed to throw exceptions. Basically, the interface is just a flag to say that the code author believes it is safe to use the new resource management syntax with the class concerned.
Fortunately, JDBC has been updated, and the appropriate classes now implement AutoCloseable. So Java can now automatically call the close() method when exiting a try block. This dramatically improves the readability of an example JDBC query. Here’s the new code:
public static void doSomething() {
try (Connection connection = DriverManager.getConnection(JDBC_URL)) {
try (PreparedStatement statement =
connection.prepareStatement("SELECT FIRST,LAST FROM
PEOPLE WHERE LAST = ?")) {
statement.setString(1, "Smith");
statement.execute();
try (ResultSet results = statement.getResultSet()) {;
while (results.next()) {
String first = results.getString(1);
String last = results.getString(2);
logger.info(first + " " + last);
}
}
}
}
}
Sure, you still need three try blocks, but the number of lines of code is almost halved.