JDBC with try with resources

匆匆过客 提交于 2021-01-27 17:18:05

问题


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;        
    }
}

回答1:


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
    }                    
}



回答2:


You should use it like this:

   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; 
    }

It didn't work because you put code in brackets.You should just put it inside these brackets -> {}. And that's also why the error showed because there is no class where there's a method that goes like:

    try(bla bla bla) {}


来源:https://stackoverflow.com/questions/38465572/jdbc-with-try-with-resources

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!