We always hear that we should close the connection once we are done with a transaction. My question here is: even if we don’t close the connection, the garbage collector will reclaim the memory once we are out of the method inside of which we are creating the connection. so what’s the actual issue, even if we don’t close the connection?
Share
No, GC doesn’t help you here, because it’s not about memory.
A connection is a scarce resource on the database server, not in your app client. If you clean up your memory without telling the server to do the same you’ll leak a connection that may not be reclaimed. Eventually you’ll run out.
Same with ResultSet – it’s a cursor.
You must always close all SQL resources – Connection, Statement, and ResultSet – in individual finally blocks, wrapped in try/catch blocks, in reverse order of acquisition.