关闭数据库连接以避免内存泄漏 [英] Closing database connection to avoid memory leak
问题描述
后续问题为关闭Java中的数据库连接
连接conn = DriverManager.getConnection(
jdbc:somejdbcvendor:某些jdbc供应商需要的其他数据,
myLogin ,
myPassword);
语句stmt = conn.createStatement();
try {
stmt.executeUpdate(INSERT INTO MyTable(name)VALUES('my name'));
} finally {
//当你完成后关闭语句很重要
stmt.close();
}
conn.close();
我知道conn.close()是必要的,但不知道为什么。
一旦方法调用结束,垃圾收集器不会释放连接对象(并释放存储在其中的每个处理程序指向数据库)。
没有。 JDBC驱动程序保留对连接的引用,因此除非可以关闭(),否则不会被清除。
创建数据库连接非常昂贵,因此您将希望尽可能回收您的连接。
Follow up question to Closing Database Connections in Java
Connection conn = DriverManager.getConnection(
"jdbc:somejdbcvendor:other data needed by some jdbc vendor",
"myLogin",
"myPassword" );
Statement stmt = conn.createStatement();
try {
stmt.executeUpdate( "INSERT INTO MyTable( name ) VALUES ( 'my name' ) " );
} finally {
//It's important to close the statement when you are done with it
stmt.close();
}
conn.close();
I know that conn.close() is necessary but do not know why. Won't the garbage collector free the connection object (and with it release every handler stored in it that points to the database), once the method call is over?
Won't the garbage collector free the connection object (and with it release every handler stored in it that points to the database), once the method call is over?
It doesn't. The JDBC driver retains a reference to to connection, so it is not cleaned up unless you can close().
BTW creating a database connection is very expensive, so you will want to recycle your connections where possible.
这篇关于关闭数据库连接以避免内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!