gpt4 book ai didi

java - 尝试使用资源的 JDBC

转载 作者:行者123 更新时间:2023-11-30 08:35:03 24 4
gpt4 key购买 nike

我正在尝试创建一个连接并返回 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 is closed”)。您应该在 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 9Java 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com