Using try-with-resources

The try-with-resources statement is a try statement that declares one or more resources that implement Java’s AutoCloseable interface (and so must have implemented a close() method).

In JDBC terms, a resource may be a Connection, Statement, ResultSet, or any other class that implements The try-with-resources statement ensures that each resource is closed (its close() method is automatically invoked) at the end of the try block.

Note that any object created in a try-with-resources statement is scoped within that try statement, it is not available in any catch or finally block belonging to the same try block.

    try (Connection dbConnection = dataSource.getConnection()) {

        try (PreparedStatement stmt = dbConnection.prepareStatement( //
                "insert into accounts (id, name, balance) values (?, ?, 0)")) {
            stmt.setInt(1, id);
            stmt.setString(2, name);
        } catch (SQLException e) {
            throw new RuntimeException("Insert failed", e);
        finally {
    } // dbConnection is closed at end of block