关闭数据库连接以避免内存泄漏 [英] Closing database connection to avoid memory leak

查看:936
本文介绍了关闭数据库连接以避免内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

后续问题为关闭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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆