我正在尝试创建一个连接并返回 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/