Skip to lesson

try-with-resources for Connection, Statement and ResultSet

Closing a connection, a statement and a result set by hand takes about fourteen lines and is easy to get wrong. Java can do the cleanup for you, whichever way the code leaves the block.

Connection, PreparedStatement and ResultSet in one try

try-with-resources is a try with a header in brackets. Every object declared in the header is closed automatically when the block ends, whether normally, by return or by an exception.

Declare each resource inside try ( ... ), separated by semicolons. A later resource may use an earlier one: conn.prepareStatement(sql) follows the Connection. Example 1 uses three.

Example 1 · The careful finally method, rewritten

Runs in: a Maven project with the MySQL driver and the ShopLite database, with max_connections set to 10

OneTryDemo.javaJava
import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;
public class OneTryDemo {    static final String URL = System.getenv("DB_URL");    static final String USER = System.getenv("DB_USER");    static final String PASSWORD = System.getenv("DB_PASSWORD");
    // The same method as the careful finally version, now in one try header    static int countProducts() throws SQLException {        try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);             PreparedStatement ps = conn.prepareStatement("SELECT COUNT(*) FROM products");             ResultSet rs = ps.executeQuery()) {            rs.next();            return rs.getInt(1);        }    }
    public static void main(String[] args) throws SQLException {        for (int request = 1; request <= 50; request++) {            int count = countProducts();            if (request % 10 == 0) {                System.out.println("Request " + request + ": " + count + " products");            }        }        System.out.println("50 requests, every connection closed");    }}
Output
Request 10: 15 products
Request 20: 15 products
Request 30: 15 products
Request 40: 15 products
Request 50: 15 products
50 requests, every connection closed

What this code does

  • Three declarations in one header replace the null variables, the finally block and its three null checks. The query has no parameters, so ps.executeQuery() can sit right in the header.
  • The return inside the block is safe: the count is read first, then all three objects are closed.
  • 50 calls on a server limited to 10 connections all succeed, so nothing leaks.

This works for any class that implements AutoCloseable, an interface with one method, close(); all the main JDBC interfaces extend it. The variables are final inside the block, and they do not exist outside it, so nobody can use a closed object by mistake.

Example 1 is the careful finally method from the previous lesson. The fourteen lines of cleanup have gone, and the behaviour is the same.

Closing order: the reverse of opening

Resources are closed in the reverse order of their declaration: the ResultSet first, then the statement, then the connection. Example 2 prints each open and each close.

Three nested boxes: the Connection holds the PreparedStatement, which holds the ResultSet. They are opened from the outside in (connection, statement, result set) and closed by try-with-resources from the inside out (result set, statement, connection).

Example 2 · Watching the closing order

CloseOrderDemo.javaJava
class Tracked implements AutoCloseable {    private final String name;
    Tracked(String name) {        this.name = name;        System.out.println("open  " + name);    }
    @Override    public void close() {        System.out.println("close " + name);    }}
public class CloseOrderDemo {    public static void main(String[] args) {        try (Tracked conn = new Tracked("connection");             Tracked ps = new Tracked("statement");             Tracked rs = new Tracked("result set")) {            System.out.println("reading rows");            throw new IllegalStateException("bad row");        } catch (IllegalStateException e) {            System.out.println("catch: " + e.getMessage());        } finally {            System.out.println("finally");        }    }}
Output
open  connection
open  statement
open  result set
reading rows
close result set
close statement
close connection
catch: bad row
finally

What this code does

  • Tracked is a tiny AutoCloseable that prints when it opens and closes, standing in for the three JDBC objects.
  • They open top to bottom and close bottom to top: result set, statement, connection.
  • All three are closed before catch runs, and finally runs last. In real code, the catch block can no longer use the connection.

That is the safe order, because each object depends on the one before it. The resources are closed before any catch or finally block of the same try runs, so in a catch the connection is already closed: log the error there, but do not use the connection. If opening one resource fails, only the ones already opened are closed.

A nested try when parameters must be set first

A PreparedStatement needs setInt and friends before executeQuery(), and a try header can hold only declarations, so the ResultSet cannot join it. The standard shape is two tries.

Java
try (Connection conn = connections.getConnection();     PreparedStatement ps = conn.prepareStatement(sql)) {    ps.setInt(1, categoryId);    try (ResultSet rs = ps.executeQuery()) {        while (rs.next()) {            // read one row        }    }}

Example 3 · Parameters first, then the inner try

Runs in: a Maven project with the MySQL driver and the ShopLite database

NestedTryDemo.javaJava
import java.math.BigDecimal;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.util.ArrayList;import java.util.List;
public class NestedTryDemo {    static final String URL = System.getenv("DB_URL");    static final String USER = System.getenv("DB_USER");    static final String PASSWORD = System.getenv("DB_PASSWORD");
    static List<String> cheaperThan(int categoryId, BigDecimal maxPrice) throws SQLException {        String sql = "SELECT name, price FROM products"                + " WHERE category_id = ? AND price <= ? AND is_active = TRUE ORDER BY price";        List<String> lines = new ArrayList<>();        try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);             PreparedStatement ps = conn.prepareStatement(sql)) {            ps.setInt(1, categoryId);                 // parameters go in between            ps.setBigDecimal(2, maxPrice);            try (ResultSet rs = ps.executeQuery()) {  // inner try for the result set                while (rs.next()) {                    lines.add(rs.getString("name") + " - Rs " + rs.getBigDecimal("price"));                }            }        }        return lines;    }
    public static void main(String[] args) throws SQLException {        System.out.println("Accessories up to Rs 2500:");        for (String line : cheaperThan(4, new BigDecimal("2500"))) {            System.out.println("  " + line);        }        System.out.println("Books up to Rs 450:");        for (String line : cheaperThan(5, new BigDecimal("450"))) {            System.out.println("  " + line);        }    }}
Output
Accessories up to Rs 2500:
  Logitech M331 Silent Mouse - Rs 849.00
  boAt Airdopes 141 - Rs 1299.00
  Mi Power Bank 20000mAh - Rs 2199.00
Books up to Rs 450:
  Atomic Habits - Rs 399.00

What this code does

  • The outer header opens the connection and the statement. The two set calls run in the body, then the inner header runs the query.
  • The rows are copied into a List<String> while the result set is open; the list is returned after both tries have closed everything.
  • Price filters use BigDecimal with setBigDecimal, never double, because these are rupee amounts.

The outer try opens the connection and the statement, and the body sets the parameters. An inner try (ResultSet rs = ps.executeQuery()) reads the rows and closes the result set; the outer block closes the rest. Example 3 runs this shape.

Order of execution

Order the two-try shape

Arrange what happens, from first to last.

Suppressed exceptions when close also fails

A suppressed exception is a second exception, thrown by close(), that Java attaches to the first one instead of replacing it. You read the attached ones with e.getSuppressed().

If the body throws and then close() throws too, for example when the network drops mid-query, Java keeps the first exception. Example 4 compares this with the old finally style.

Example 4 · The real error survives with try-with-resources

SuppressedDemo.javaJava
class BrokenConnection implements AutoCloseable {    @Override    public void close() throws Exception {        throw new Exception("close failed: network gone");    }}
public class SuppressedDemo {    static void withFinally() throws Exception {        BrokenConnection conn = new BrokenConnection();        try {            throw new Exception("query failed: Unknown column 'prise'");        } finally {            conn.close();                           // this exception replaces the query error        }    }
    static void withTryWithResources() throws Exception {        try (BrokenConnection conn = new BrokenConnection()) {            throw new Exception("query failed: Unknown column 'prise'");        }    }
    public static void main(String[] args) {        try {            withFinally();        } catch (Exception e) {            System.out.println("finally version   : " + e.getMessage());            System.out.println("  suppressed      : " + e.getSuppressed().length);        }
        try {            withTryWithResources();        } catch (Exception e) {            System.out.println("try-with-resources: " + e.getMessage());            for (Throwable s : e.getSuppressed()) {                System.out.println("  suppressed      : " + s.getMessage());            }        }    }}
Output
finally version   : close failed: network gone
  suppressed      : 0
try-with-resources: query failed: Unknown column 'prise'
  suppressed      : close failed: network gone

What this code does

  • In the finally version, the close exception replaces the query error. The caller sees close failed and never learns about the misspelt column prise.
  • In the try-with-resources version, the query error is the one thrown, and the close failure is kept in getSuppressed().
  • Logging frameworks print suppressed exceptions under a Suppressed: line in the stack trace, so both problems reach the log.

The old finally style does the opposite: an exception thrown in finally replaces the original one, so the log shows close failed and the real cause, such as a typo in a column name, is lost.

Returning results safely from inside a try

A return inside the block is fine: Java works out the value, closes the resources, then leaves the method. Examples 5 and 6 show what goes wrong when the value is a ResultSet.

Example 5 · Mistake: returning the ResultSet

Runs in: a Maven project with the MySQL driver and the ShopLite database

ReturnResultSetBug.javaJava
import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;
public class ReturnResultSetBug {    static final String URL = System.getenv("DB_URL");    static final String USER = System.getenv("DB_USER");    static final String PASSWORD = System.getenv("DB_PASSWORD");
    // BUG: the result set leaves the try block, but it is closed on the way out    static ResultSet findCategories() throws SQLException {        try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);             PreparedStatement ps = conn.prepareStatement("SELECT name FROM categories ORDER BY name");             ResultSet rs = ps.executeQuery()) {            return rs;        }    }
    public static void main(String[] args) {        try {            ResultSet rs = findCategories();            while (rs.next()) {                System.out.println(rs.getString("name"));            }        } catch (SQLException e) {            System.out.println(e.getClass().getName() + ": " + e.getMessage());        }    }}
Output
java.sql.SQLException: Operation not allowed after ResultSet closed

What this code does

  • return rs; hands back a result set that the try header closes on the way out, together with its statement and connection.
  • The caller's first rs.next() fails with Operation not allowed after ResultSet closed. Removing rs from the header would only swap this error for a leak.

Example 6 · The fix: return plain Java objects

Runs in: a Maven project with the MySQL driver and the ShopLite database

ReturnSafelyDemo.javaJava
import java.math.BigDecimal;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.util.ArrayList;import java.util.List;import java.util.Optional;
record Product(int id, String name, BigDecimal price, int stock) {}
public class ReturnSafelyDemo {    static final String URL = System.getenv("DB_URL");    static final String USER = System.getenv("DB_USER");    static final String PASSWORD = System.getenv("DB_PASSWORD");    static final String COLUMNS = "SELECT product_id, name, price, stock FROM products";
    static Product mapRow(ResultSet rs) throws SQLException {        return new Product(rs.getInt("product_id"), rs.getString("name"),                rs.getBigDecimal("price"), rs.getInt("stock"));    }
    static Optional<Product> findById(int id) throws SQLException {        try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);             PreparedStatement ps = conn.prepareStatement(COLUMNS + " WHERE product_id = ?")) {            ps.setInt(1, id);            try (ResultSet rs = ps.executeQuery()) {                if (rs.next()) {                    return Optional.of(mapRow(rs));   // the record is built before anything closes                }                return Optional.empty();            }        }    }
    static List<Product> findByCategory(int categoryId) throws SQLException {        try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);             PreparedStatement ps = conn.prepareStatement(COLUMNS + " WHERE category_id = ? ORDER BY name")) {            ps.setInt(1, categoryId);            try (ResultSet rs = ps.executeQuery()) {                List<Product> products = new ArrayList<>();                while (rs.next()) {                    products.add(mapRow(rs));                }                return products;                       // plain Java objects, safe to use after closing            }        }    }
    public static void main(String[] args) throws SQLException {        System.out.println(findById(3));        System.out.println(findById(99));        for (Product p : findByCategory(3)) {            System.out.println(p.name() + " | Rs " + p.price() + " | stock " + p.stock());        }    }}
Output
Optional[Product[id=3, name=iPhone 15 128GB, price=69900.00, stock=8]]
Optional.empty
HP Victus 15 Gaming | Rs 64990.00 | stock 5
Lenovo IdeaPad Slim 3 | Rs 42990.00 | stock 12

What this code does

  • findById returns Optional<Product>, built by mapRow while the row is still readable; Optional.empty() covers a missing id.
  • findByCategory collects records into a List and returns it. The caller works with plain Java objects that do not depend on any open connection.
  • One mapRow method is shared by every query, so the column names live in one place.

A returned ResultSet is already closed by the time the caller sees it, and the first rs.next() throws SQLException: Operation not allowed after ResultSet closed. Copy the rows into plain Java objects (a record, a List, an Optional) and return those, built while the result set is still open.

Two related rules:

  • Never return or store a Connection or Statement either: the block closes them too.
  • Need several queries? Use one connection and give each statement and result set its own small try.

Next step

Check your understanding

12 quick questions