Reopen database connection in Java

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

+7
source share
5 answers

I am not 100% sure that you need to call DriverManager.getConnection() , but what harm? You have already closed the connection, just take a new one when you need it. The garbage collector takes care of this closed connection after you drop it.

+4
source

If you called connection.close(); , connection (assuming java.sql.Connection ) becomes useless. This operation releases this database of connection objects and JDBC resources.

So Yes, you need to get a new connection before you can continue.

 connection = DriverManager.getConnection() 
+7
source

Yes, you cannot do anything after closing the connection. you have to call getConnection

+1
source

As Javadoc mentions:

 getConnection: Attempts to establish a connection to the given database URL. 

So yes, calling getConnection () again looks like the only way to establish a new database connection as soon as you close the previous connection.

0
source

Good. Ideally, I took a slightly different approach and gave a different solution.

Instead of opening and closing the database, which literally happens for every client request, I made a singleton instance of the class and made one open connection, which will be reused until the server process is alive.

In short:

I have getConnection() inside a Database class

  public Connection getConnection() throws Exception { try { String connectionURL = "jdbc:mysql://localhost:3306/someDatabase"; Class.forName("com.mysql.jdbc.Driver").newInstance(); if (connection == null) { connection = DriverManager.getConnection(connectionURL, "someUser", LOCAL_MYSQL_PASSWORD); } return connection; } catch (Exception e) { } } 

The Database class is single-point, so reusing the same class and reusing the same connection.

I tested this with show processList and it gave about 100 connections. If I don’t close the connection, and even if I close the connection, the actual process is unlikely to be killed, but instead it will be used when the same client requests the same request, but if you have 15 requests, each of them will have separate processes, so closing and opening the connection for me was not the best solution.

In doing so, I have one single process, which is the responsible layer for requests.

0
source

All Articles