Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reopen database connection in Java

Tags:

java

jdbc

After closing a database connection in java, can I reopen it? Or do I need to do DriverManager.getConnection() again?

like image 480
Jiew Meng Avatar asked Apr 06 '12 13:04

Jiew Meng


People also ask

How do I reopen a closed connection in Java?

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.

What happens if DB connection is not closed Java?

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.

Why should we close database connections in Java?

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.

Does JDBC automatically close connection?

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.


3 Answers

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.

like image 31
Scott M. Avatar answered Oct 13 '22 19:10

Scott M.


yes, you cant do anything after closing connection. you have to call getConnection

like image 43
Nirmal- thInk beYond Avatar answered Oct 13 '22 19:10

Nirmal- thInk beYond


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()
like image 78
ring bearer Avatar answered Oct 13 '22 18:10

ring bearer