Java 教程声明您可以使用以下方法执行以下操作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) {
}