我正在尝试创建一个连接并返回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;
}
}
答案 0 :(得分:4)
当您使用try-with-resources时,必须在try-with-resources
块内声明指向可关闭资源的变量。
此外,返回rs
是一个坏主意,它将在方法完成后关闭。因此,您可能会在方法之外得到SQLException
(类似“ResultSet已关闭”)。您应该在rs
块内部解析try-with-resources
并从您的方法返回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
语法上遇到编译时错误,就是这样。
答案 1 :(得分:-2)
您应该像这样使用它:
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;
}
它没有用,因为你把代码放在括号中。你应该把它放在这些括号中 - > {}。这就是为什么错误显示的原因,因为没有一个类,其中有一个类似的方法:
try(bla bla bla) {}