Does closing a java.sql.Connection
also close all the statements,
prepared statements, etc. obtained
from that connection? Or is there
going to be memory leak if I close the
connection but leave the statements,
etc. unclosed?
你不应该依赖它.
规范如下:
An application calls the method
Statement.close to indicate that it
has finished processing a statement.
All Statement objects will be closed
when the connection that created them
is closed. 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.
最佳做法是在finally块中关闭所有ResultSet,Statements和Connections,每个ResultSet都包含在它们自己的try / catch中,与获取的顺序相反.
写一个这样的类:
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
}
像这样打电话:
Statement s;
try
{
// JDBC stuff here
}
finally
{
DatabaseUtils.close(s);
}