【发布时间】:2016-04-20 19:45:05
【问题描述】:
Java tutorial 状态,您可以使用try-with-resources 执行以下操作:
try (Statement stmt = con.createStatement()) {
ResultSet rs = stmt.executeQuery(query);
...
} catch (SQLException e) {
...
}
在本教程中 ResultSet 永远不会关闭,因此我想包含 ResultSet ,因为它还实现了 AutoCloseable 接口,如下所示:
try (Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query)) {
...
} catch (SQLException e) {
...
}
这很好用,但是当涉及到PreparedStatements 时,我希望能够在 执行查询之前设置一些值:
String name = "Ian";
try (PreparedStatement pstmt = getPreparedStatement(con, stmt);
pstmt.setString(1, name);
ResultSet rs = pstmt.executeQuery(query)) {
...
} catch (SQLException e) {
...
}
这会导致一系列编译错误,因为(我假设)只允许变量赋值。
有没有办法在同一个try-with-resources 块中巧妙地做到这一点?
我已经想到了:
- 嵌套的 try-with-resources(这是我试图避免的)。我意识到这样做并没有什么“错误”,我只是为了可读性而这样做。
考虑以下情况:
try (MyObject1 o1 = new MyObject1()) {
o1.setSomeValue();
try (MyObject2 o2 = new MyObject2(o1)) {
o2.setSomeValue();
try (MyObject3 o3 = new MyObeject3(o2) {
o3.setSomeValue();
// do work here
}
}
} catch (Exception e) {
...
}
对
try (MyObject1 o1 = new MyObject1();
o1.setSomeValue();
MyObject3 o2 = new MyObeject2(o1);
o2.setSomeValue();
MyObject3 o3 = new MyObeject3(o2);
o3.setSomeValue()) {
// do work here
} catch (Exception e) {
...
}
- 让
setString()方法返回对象并将其包含在赋值中 - 创建某种帮助方法来创建连接并相应地设置参数。
类似:
public PreparedStatement createPreparedStatement(Connection con, String stmt, Object ... params) {
}
【问题讨论】:
-
您可以使用嵌套的
try而不使用catch。这将关闭ResultSet,并且任何发生的异常都将由外部 catch 块处理。
标签: java prepared-statement try-with-resources autocloseable