Monday, February 6, 2012

JDBC 4.1: 'try-with-resources' Statement Automatically Close Resources

Before Java 7, the biggest worry while working with JDBC was to close the resources. If we don’t close them, we can be left with unclosed resources to the database. This means that we could eventually run out of resources.

Java 7 solves this problem by introducing a 'try-with-resources' statement which automatically close resources of type java.sql.Connection, java.sql.Statement, and java.sql.ResultSet objects, regardless of whether a SQLException or any other exception has been thrown. A try-with-resources statement consists of a try statement and one or more declared resources. This statement ensures that any resources declared in the try statement will be closed automatically.

NOTE: If multiple resources variables are declared in try statement, they are closed in reverse order in which they are declared.


public static void showEmployees(Connection con) throws SQLException 
    String query = "select EMP_NAME, EMP_ID, EMP_ADDRESS, 
                     EMP_DESIGNATION from EMPLOYEES";

    try (Statement stmt = con.createStatement()) 
        ResultSet rs = stmt.executeQuery(query);

        while ( 
            String empName = rs.getString("EMP_NAME");
            int empID = rs.getInt("EMP_ID");
            String empAddress = rs.getFloat("EMP_ADDRESS");
            String empDesignation = rs.getInt("EMP_DESIGNATION");
            System.out.println(empName + ", " + empID + ", " + 
                      empAddress + ", " + empDesignation);

The above highlighted statement is a try-with-resources statement declares one resource stmt which will be automatically closed as soon as try block terminates.

No comments: