问题描述
是否需要在一个db.getConnection()中关闭ResultSet和PreparedStatement?对于下面的示例:
Is it necessary to close ResultSet and PreparedStatement within one db.getConnection()? For the example below:
Connection conn = db.getConnection();
PreparedStatement pstmt = conn.prepareStatement(firstsql);
ResultSet r = pstmt.executeQuery();
// do something with the ResultSet
r.close();
pstmt.close(); // do I need close the r and pstmt here?
PreparedStatement pstmt = conn.prepareStatement(secondsql);
ResultSet r = pstmt.executeQuery();
// do something with the ResultSet again
r.close();
pstmt.close();
conn.close();
return null;
第5行和第6行的代码是否必要?
Are the codes of line 5 and line 6 necessary?
推荐答案
严格来说,没有必要,因为您可以同时打开多个准备好的语句。 必要的是是关闭所有打开的资源,如果以后不再使用它。
Strictly speaking, it is not necessary because you can have multiple prepared statements opened at the same time. What is necessary is to close every opened resource if it is not going to be utilised later.
看看您的代码,并不能确保该语句实际上是关闭的。
Looking at your code, it doesn't ensure that the statement are, in fact, closed.
为了确保这一点,每个关闭操作必须在 finally
块内完成:这样,它将执行该操作是否成功。
To ensure this, every close operation must be done inside a finally
block: this way, it will executed whether the operation succeded or not.
示例代码:
PreparedStatement pstmt = null;
ResultSet r = null;
try {
pstmt = conn.prepareStatement(firstsql);
r = pstmt.executeQuery();
// do something with the ResultSet
} finally {
if (r != null) {
try {
r.close();
} catch (SQLException e) {
//log error
}
}
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException e) {
//log error
}
}
}
//and do it again
如果您将Java 7与语句:
This code can be greatly simplified if you are using Java 7 with the try-with-resources statement:
try (PreparedStatement pstmt = conn.prepareStatement(firstsql);
ResultSet r = pstmt.executeQuery();) {
// do something with the ResultSet
}
这篇关于在准备另一个语句之前是否需要关闭PreparedStatement的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!