[英]Which should I close first, the PreparedStatement or the Connection?
When using a PreparedStatement
in JDBC, should I close the PreparedStatement
first or the Connection
first? 在JDBC中使用
PreparedStatement
时,我应该首先关闭PreparedStatement
还是首先关闭Connection
? I just saw a code sample in which the Connection
is closed first, but it seems to me more logical to close the PreparedStatement
first. 我刚看到一个代码示例,其中
Connection
首先被关闭,但在我看来首先关闭PreparedStatement
更合乎逻辑。
Is there a standard, accepted way to do this? 是否有标准的,可接受的方式来做到这一点? Does it matter?
有关系吗? Does closing the
Connection
also cause the PreparedStatement
to be closed, since the PreparedStatement
is directly related to the Connection
object? 关闭
Connection
是否也会导致PreparedStatement
关闭,因为PreparedStatement
与Connection
对象直接相关?
The statement. 该声明。 I would expect you to close (in order)
我希望你关闭(按顺序)
(and check for nulls along the way!) (并检查沿途的空值!)
ie close in reverse order to the opening sequence. 即以与开启顺序相反的顺序关闭。
If you use Spring JdbcTemplate (or similar) then that will look after this for you. 如果你使用Spring JdbcTemplate (或类似的),那么它将为你照顾。 Alternatively you can use Apache Commons DbUtils and
DbUtils.close()
or DbUtils.closeQuietly()
. 或者,您可以使用Apache Commons DbUtils和
DbUtils.close()
或DbUtils.closeQuietly()
。
The following procedures should be done (in order) 应该完成以下程序(按顺序)
ResultSet
ResultSet
PreparedStatement
PreparedStatement
Connection
. Connection
。 Also, it's advisable to close all JDBC related objects in the finally
close to guarantee closure. 此外,建议关闭
finally
close中的所有JDBC相关对象以保证闭包。
//Do the following when dealing with JDBC. This is how I've implemented my JDBC transactions through DAO....
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = ....
ps = conn.prepareStatement(...);
//Populate PreparedStatement
rs = ps.executeQuery();
} catch (/*All relevant exceptions such as SQLException*/Exception e) {
logger.error("Damn, stupid exception: " , e);
} finally {
if (rs != null) {
try {
rs.close();
rs = null;
} catch (SQLException e) {
logger.error(e.getMessage(), e.fillInStackTrace());
}
}
if (ps != null) {
try {
ps.close();
ps = null;
} catch (SQLException e) {
logger.error(e.getMessage(), e.fillInStackTrace());
}
}
try {
if (conn!= null && !conn.isClosed()){
if (!conn.getAutoCommit()) {
conn.commit();
conn.setAutoCommit(true);
}
conn.close();
conn= null;
}
} catch (SQLException sqle) {
logger.error(sqle.getMessage(), sqle.fillInStackTrace());
}
}
You can see I've checked if my objects are null and for connection, check first if the connection is not autocommited. 您可以看到我已检查我的对象是否为空并且是否为连接,请首先检查连接是否未自动更新。 Many people fail to check it and realise that the transaction hasn't been committed to DB.
许多人未能检查它并意识到事务尚未提交给DB。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.