After closing a database connection in java, can I reopen it? Or do I need to do DriverManager.getConnection()
again?
No, you cannot reopen a closed connection. It's a dead object for the most part and one that represents a physically dead connection. Data sources create a new connection on getConnection(), as described in the API.
If we don't close the connection, it will lead to connection memory leakage. Until application server/web server is shut down, connection will remain active, even if the user logs out.
It's always a best practice to close the connections on your own, without depending on other drivers and templates to handle closing. Failure of closing the connection will result in the sockets and resources open forever until a crash(no more resource scenario) or restart.
Once the execution exits the try block, the JDBC Connection will get closed automatically for you. That way you do not forget to close the JDBC Connection yourself.
I'm not 100% sure that you need to call DriverManager.getConnection()
but what's the harm? You already closed the connection, just grab a new one when you need it. The garbage collector worries about that closed connection after you discard it.
yes, you cant do anything after closing connection. you have to call getConnection
If you had called connection.close();
, the connection
(assuming java.sql.Connection
type) becomes useless. This operation releases this Connection object's database and JDBC resources.
So Yes you need to get a fresh connection when before you can proceed by
connection = DriverManager.getConnection()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With