Search code examples
javajdbctry-with-resources

JDBC with try with resources


I am trying to create a centralized class that connects and returns the ResultSet of a SQL query so that I don't always have to create a new connection every time I am trying to get a query.

I am using the try-with-resources, however, I am getting a compile-time error whenever I use the try-with-resources and I don't know why?

public class JDBC {

    // logger declaration is omitted

    private static final String dbURL = "jdbc:oracle:";
    private static final String userName = "blah";
    private static final String password = "12345";

    public ResultSet retrieveSQLQuery(String sqlQuery) {            
        Connection conn = null;
        Statement statement = null;
        ResultSet rs = null;

        try (conn = DriverManager.getConnection(dbUrl, user, password);
             statement = conn.createStatement();
             rs = statement.executeQuery(sqlQuery)) {               

        } catch (SQLException e) {
            logger.info(e.getMessage());
        }                    
        return rs;        
    }
}

Solution

  • Java 7

    When you use try-with-resources, variables pointing to Closeable resources must be declared inside try-with-resources block.

    Moreover, returning rs is a bad idea, it would be closed after method is done. So you might get an SQLException outside your method (something like "ResultSet is closed"). You should parse rs inside try-with-resources block and return SQL agnostic object from your method:

    public ResultSet retrieveSQLQuery(String sqlQuery) {            
        try (Connection conn = DriverManager.getConnection(dbUrl, user, password);
             Statement statement = conn.createStatement();
             ResultSet rs = statement.executeQuery(sqlQuery)) {
            MyResult result = ...; // parse rs here
            return myResult;               
        } catch (SQLException e) {
            logger.info(e.getMessage());
            // return something (empty MyResult or null) from here or rethrow the exception
            // I'd recommend to get rid of this catch block and declare the SQLException on method signature
        }                    
    }
    

    You're getting compile-time error on incorrect try-with-resources syntax, that's it.


    Update

    Java 9 Java 9 provides more flexible syntax for try-with-resources. You can declare Closeable resource outside the try (...) block:

    public ResultSet retrieveSQLQuery(String sqlQuery) {
        Connection conn = DriverManager.getConnection(dbUrl, user, password);
        try (conn; ResultSet rs = conn.createStatement().executeQuery(sqlQuery)) {
            MyResult result = ...; // parse rs here
            return myResult;               
        } catch (SQLException e) {
            // handle error
        }                    
    }