Java tutorial声明您可以使用 try-with-resources
执行以下操作:
try (Statement stmt = con.createStatement()) {
ResultSet rs = stmt.executeQuery(query);
...
} catch (SQLException e) {
...
}
在本教程中, ResultSet
永远不会关闭,因此我想包含 ResultSet
,因为它还实现了 AutoCloseable
接口(interface),例如所以:
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
block 中巧妙地完成此操作?
我已经想到了:
- 嵌套的 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) {
}
最佳答案
我猜你的意思是Connection.prepareStatement()
。
无需显式关闭 ResultSet,因为 Statement.close
的 API 文档保证关闭其 ResultSet。所以这样写就可以了
try (PreparedStatement stmt = con.prepareStatement(query)) {
stmt.setString(1, name);
ResultSet rs = stmt.executeQuery(query);
...
}
catch (SQLException e) {
...
}
关于java - 在 try-with-resources block 中调用对象的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34807274/