即使在 Java 7 中,我也经常看到类似的代码
Connection c = null;
PreparedStatement s = null;
try {
c = dataSource.getConnection();
String sql = "insert into table (column1, column2) values (?, ?);
s = c.prepareStatement(sql);
int i = 1;
s.setString(i++, "111");
s.setString(i++, "222");
s.execute();
} catch (SQLException e) {
log.error("failed to insert", e);
} finally {
DbUtils.close(s, c); // closes s and c with no questions
}
但根据规范,当连接关闭时,所有语句和结果集都会被释放。
我听说 JDBC 驱动程序有可能不遵守 JDBC API 的规则,而旧的方法更好。我的问题是想听听对此的意见。代码看起来更好,但是如果它很危险怎么办? 在我看来,最喜欢的方法是在这里使用 try-with-resources 。足够安全吗?
最佳答案
资源是一个对象,在程序使用完它后必须关闭它。因此您不必在finally
block 中手动关闭该对象
String sql = "insert into table (column1, column2) values (?, ?);
try(Connection c = dataSource.getConnection();
PreparedStatement s = c.prepareStatement(sql);) {
int i = 1;
s.setString(i++, "111");
s.setString(i++, "222");
s.execute();
} catch (SQLException e) {
log.error("Failed to insert transaction", e);
}
关于java - JDBC资源的正确使用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23138189/