Akhil K Nambiar
Akhil K Nambiar

Reputation: 3975

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.

Upvotes: 0

Views: 78

Answers (2)

Brett Okken
Brett Okken

Reputation: 6306

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.

Upvotes: -1

Matt Ball
Matt Ball

Reputation: 359776

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);
}

Upvotes: 3

Related Questions