After closing a database connection in java, can I reopen it? Or do I need to do DriverManager.getConnection() again?
5 Answers
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() 1 Comment
As Javadoc mentions:
getConnection: Attempts to establish a connection to the given database URL. Therefore yes, calling getConnection() again looks like the only way to establish a new connection with database once you closed previous connection.
Comments
Well Ideally I made slightly different approach and gave a different solution.
Instead of opening and closing the database, which literally happening on every request of the client, I made a singleton instance of a class and made single open connection which will be reused as long as the process of the server is alive.
In short:
I have getConnection() inside 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 singleton, hence reusing the same class and reusing the same connection.
I've tested this by show processList, and this one was giving around 100 connections If I won't close the connection, and even If I close the connection, actual process will not likely to be killed, but put into sleep instead so it will be used whenever the same client will ask for same request, but if you have like 15 requests, then each of them will have separate processes, so closing and opening connection for me wasn't best solution.
By this I have 1 single process which is responsible layer for queries.
getConnectionwill work, tried it, but isit the "correct" way?