java - 带有尝试资源的 JDBC

标签 java jdbc try-with-resources

我正在尝试创建一个连接并返回 SQL 查询的 ResultSet 的集中式类,这样我就不必每次尝试获取查询时都创建一个新连接.

我正在使用 try-with-resources,但是,每当我使用 try-with-resources 时,我都会收到编译时错误,但我不这样做不知道为什么?

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

最佳答案

Java 7

当您使用try-with-resources时,指向 Closeable 资源的变量必须在 try-with-resources block 内声明。

此外,返回rs是一个坏主意,它会在方法完成后关闭。因此,您可能会在方法之外收到 SQLException(类似于“ResultSet 已关闭”)。您应该在 try-with-resources block 中解析 rs 并从您的方法返回与 SQL 无关的对象:

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

由于 try-with-resources 语法不正确,您会收到编译时错误,就是这样。


更新

Java 9 Java 9 为 try-with-resources 提供了更灵活的语法。您可以在 try (...) block 之外声明 Closeable 资源:

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

关于java - 带有尝试资源的 JDBC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38465572/

相关文章:

java - XPath 表达式不为//元素返回任何内容,但//* 返回一个计数

java - 如何管理与动态创建的数据库的连接

java - 如何通过 Android 中的 asynctask 从 Hashmap 获取输出?

java - 在 Java 8 中正确使用 URLConnection 和 try-with-resources

java - 谁捕获异常,在 close 方法中出现?(try-with-resources)

Java RegEx 全部替换以格式化 XML 中的数据

java - surefire 插件的 JDK-13 不支持的类文件主要版本

java - 将 float 组有效转换为字节数组

java.lang.AbstractMethodError : com. mysql.jdbc.Connection.isValid(I)Z 错误

java - Java8中 "Autocloseable"的数组或集合