Using try-with-resources

The NuoDB JDBC driver is based on JDBC 4.0 and 4.1. If using JDK greater than 1.6, the try-with-resources feature is recommended. The try-with-resources statement is a try statement that declares one or more resources. In JDBC terms, a resource may be a Statement, a ResultSet, or any other class that implements java.io.AutoCloseable. The try-with-resources statement ensures that each resource is closed (i.e. close() is called) at the end of the statement. Here is a snippet from HelloDB.java without using try-with-resources.

Statement stmt = dbConnection.createStatement();
ResultSet rs = stmt.executeQuery("select balance from accounts where id=" + id);
try {
    if (rs.next())
        return rs.getString(1);
    return null;
} finally {
    rs.close();
    stmt.close();
}

You see we need to include a finally clause to close the ResultSet and Statement. Here is the same code written with try-with-resources:

try ( Statement stmt = dbConnection.createStatement();
      ResultSet rs = stmt.executeQuery(
          "select balance from accounts where id=" + id) ) {
    if (rs.next())
        return rs.getString(1);
    return null;
}