[英]Impact of java.sql.Connection.close() on java.sql.Statement objects and the like
Does closing a java.sql.Connection
also close all the statements, prepared statements, etc. obtained from that connection? 关闭java.sql.Connection
是否也会关闭从该连接获得的所有语句,预处理语句等? Or is there going to be memory leak if I close the connection but leave the statements, etc. unclosed? 或者,如果我关闭连接但是保留语句等未公开会导致内存泄漏吗?
Does closing a java.sql.Connection also close all the statements, prepared statements, etc. obtained from that connection? 关闭java.sql.Connection是否也会关闭从该连接获得的所有语句,预处理语句等? Or is there going to be memory leak if I close the connection but leave the statements, etc. unclosed? 或者,如果我关闭连接但是保留语句等未公开会导致内存泄漏吗?
You should not depend on it. 你不应该依赖于它。
The spec reads as follows: 规范如下:
An application calls the method Statement.close to indicate that it has finished processing a statement. 应用程序调用Statement.close方法来指示它已完成处理语句。 All Statement objects will be closed when the connection that created them is closed. 关闭创建它们的连接时,将关闭所有Statement对象。 However, it is good coding practice for applications to close statements as soon as they have finished processing them. 但是,应用程序在完成处理后立即关闭语句是一种很好的编码实践。 This allows any external resources that the statement is using to be released immediately. 这允许立即释放语句正在使用的任何外部资源。
The best practice is to close ALL ResultSets, Statements, and Connections in a finally block, each enclosed in their own try/catch, in reverse order of acquisition. 最佳做法是在finally块中关闭所有ResultSet,Statements和Connections,每个ResultSet都包含在它们自己的try / catch中,与获取的顺序相反。
Write a class like this: 写一个这样的类:
public class DatabaseUtils
{
public static void close(Statement s)
{
try
{
if (s != null)
{
s.close();
}
}
catch (SQLException e)
{
// log or report in someway
e.printStackTrace();
}
}
// similar for ResultSet and Connection
}
Call like this: 像这样打电话:
Statement s;
try
{
// JDBC stuff here
}
finally
{
DatabaseUtils.close(s);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.