如果我通过在connection对象上调用close()来显式地关闭连接,那么我已经将connection对象设置为null。connection对象的close()和null有什么区别?如果我关闭连接,连接对象还会保留在连接池中吗?例如
Connection dbConnection=null;
PreparedStatement preparedStatement = null;
ResultSet rs;
try {
Connection dbConnection= DriverManager.getConnection("jdbc:hsqldb:file:test5","sa", "");
...........
...........
dbConnection.close();
dbConnection=null;
} catch (Exception e) {
LOGGER.error("Exception Occured while fetching All record:Item details start method "
+ e.getMessage());
} finally {
try
{
if (rs!=null)
{
rs.close();
rs=null;
}
}
catch(SQLException e)
{
LOGGER.error(RESULTSETCLOSEEXCEPTION
+ e.getMessage());
}
try {
if (preparedStatement != null) {
preparedStatement.close();
preparedStatement=null;
}
} catch (SQLException e) {
LOGGER.error(STATEMENTCLOSEEXCEPTION
+ e.getMessage());
}
try {
if (dbConnection != null) {
dbConnection.close();
dbConnection=null;
}
} catch (SQLException e) {
LOGGER.error(CONNECTIONCLOSEEXCEPTION
+ e.getMessage());
}
}上面的代码是关闭连接、预置语句和结果集的正确方式吗?
发布于 2013-08-19 14:36:05
一个关闭连接,另一个将连接引用设置为null。
如果您不关闭连接,您可能会有连接泄漏。在finally块中关闭连接是很重要的。
close()操作关闭连接--it‘t do anything to The connection reference。您可能无法对该连接执行任何操作,但它不是null。一旦它被关闭,它就可以被释放回一个收集池,但这又是不同的东西。
结论:: *connection.close()*它关闭与数据库的连接并释放所有资源。***con = null*** -在这种情况下,删除对connection对象的引用。如果连接是打开的,那么它仍然是打开的,即资源不是空闲的。
如果我说错了,请让我改正。
发布于 2013-08-19 14:27:28
从文档中找到。
close()
Releases this Connection object's database and JDBC resources immediately instead of
waiting for them to be automatically released.发布于 2014-09-19 19:53:36
通过使用Connection.close(),我们可以关闭资源并重用连接,因为它会返回并存储到连接池中
和
通过使Connection connection = null有意义,我们释放了连接资源,这样在内存管理中没有泄漏,但我们不能重用它。
https://stackoverflow.com/questions/18307524
复制相似问题