简体   繁体   中英

Closing a DB connection in Java

Its just a foolish queation from a java programmer. I have something like

PreparedStatement stmt = DBConnection.getConnection()
                .prepareStatement(sql);

Now in finally block I check if stmt exists and then close it. What will happen to Connection object in this case. I know if I write in separate lines then I can close it as I have a reference to connection object which I don't have in this case.

What will happen to Connection object in this case.

Nothing. There is no magic, so the connection isn't magically closed, just because you didn't assign it to a variable.

That's why you use a separate variable for the Connection : so you can call close() ! Or use try-with-resources:

try (Connection connection = DBConnection.getConnection()) {
    PreparedStatement stmt = connection.prepareStatement(sql);
}

The connection will remain open until it is garbage collected at some time in the future.

However, in the case of connection pools, yours might not be the only reference to the Connection (if the pool also maintains a reference to connections which have been borrowed). In this case garbage collection will not take place, and the collection will not be closed. It will have "leaked" from the pool, which will likely eventually cause the pool to be exhausted and no further connections will be available.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM