我最近和我的教授讨论了如何处理基本的 jdbc 连接方案。假设我们要执行两个查询,这是他提出的
public void doQueries() throws MyException{
Connection con = null;
try {
con = DriverManager.getConnection(dataSource);
PreparedStatement s1 = con.prepareStatement(updateSqlQuery);
PreparedStatement s2 = con.prepareStatement(selectSqlQuery);
// Set the parameters of the PreparedStatements and maybe do other things
s1.executeUpdate();
ResultSet rs = s2.executeQuery();
rs.close();
s2.close();
s1.close();
} catch (SQLException e) {
throw new MyException(e);
} finally {
try {
if (con != null) {
con.close();
}
} catch (SQLException e2) {
// Can't really do anything
}
}
}
我不喜欢这种方法,对此我有两个问题:
1.A)我认为,如果在我们做“其他事情”的地方抛出任何异常,或者在该行中,或者在rs.close()
方法结束s2.close()
时s1
不会被关闭。我说得对吗?
1.B)教授一直要求我明确关闭结果集(即使声明文档明确表示它将关闭结果集)她说 Sun 推荐它。有什么理由这样做吗?
现在这是我认为是同一件事的正确代码:
public void doQueries() throws MyException{
Connection con = null;
PreparedStatement s1 = null;
PreparedStatement s2 = null;
try {
con = DriverManager.getConnection(dataSource);
s1 = con.prepareStatement(updateSqlQuery);
s2 = con.prepareStatement(selectSqlQuery);
// Set the parameters of the PreparedStatements and maybe do other things
s1.executeUpdate();
ResultSet rs = s2.executeQuery();
} catch (SQLException e) {
throw new MyException(e);
} finally {
try {
if (s2 != null) {
s2.close();
}
} catch (SQLException e3) {
// Can't do nothing
}
try {
if (s1 != null) {
s1.close();
}
} catch (SQLException e3) {
// Can't do nothing
}
try {
if (con != null) {
con.close();
}
} catch (SQLException e2) {
// Can't do nothing
}
}
}
2.A)这段代码正确吗?(是否保证方法结束时全部关闭?)
2.B)这是非常大且冗长的(如果有更多的语句,它会变得更糟)是否有任何更短或更优雅的方法可以在不使用 try-with-resources 的情况下做到这一点?
最后这是我最喜欢的代码
public void doQueries() throws MyException{
try (Connection con = DriverManager.getConnection(dataSource);
PreparedStatement s1 = con.prepareStatement(updateSqlQuery);
PreparedStatement s2 = con.prepareStatement(selectSqlQuery))
{
// Set the parameters of the PreparedStatements and maybe do other things
s1.executeUpdate();
ResultSet rs = s2.executeQuery();
} catch (SQLException e) {
throw new MyException(e);
}
}
3)这段代码正确吗?我认为我的教授不喜欢这种方式,因为没有明确关闭 ResultSet,但她告诉我,只要在文档中清楚地表明所有内容都已关闭,她就可以接受。您能否提供任何带有类似示例的官方文档链接,或者根据文档显示此代码没有问题?