所以我遇到了一些代码,并想知道使用嵌套的try-with-resource语句和使用单个try-with-resource与多个资源之间的区别是什么?
private void doEverythingInOneSillyMethod(String key)
throws MyAppException
{
try (Connection db = ds.getConnection()) {
db.setReadOnly(true);
...
try (PreparedStatement ps = db.prepareStatement(...)) {
ps.setString(1, key);
...
try (ResultSet rs = ps.executeQuery()) {
...
}
}
} catch (SQLException ex) {
throw new MyAppException("Query failed.", ex);
}
}
VS
private void doEverythingInOneSillyMethod(String key)
throws MyAppException {
try (Connection db = ds.getConnection();
PreparedStatement ps = db.prepareStatement(...);
ResultSet rs = ps.executeQuery();) {
db.setReadOnly(true);
ps.setString(1, key);
} catch (SQLException ex) {
throw new MyAppException("Query failed.", ex);
}
}
前者有什么好处吗?