Connection Manager as singleton

51 views Asked by At

Suppose that I created object to managing connection as signleton, for example:

public class DatabaseConnection {

private static Connection con = null;

static

{ 

String url = "jdbc:`\[`mysql:/`\](mysql://)`/localhost:3306/org";`

String user = "root";
String pass = "root";

try {

Class.forName("com.mysql.jdbc.Driver");

con = DriverManager.getConnection(url, user, pass);

}

catch (ClassNotFoundException | SQLException e) {

e.printStackTrace();

}

}

public static Connection getConnection()

{

return con;
}

}

Do I understand correctly that with this approach I created only one instance of connection and use it in the whole application. I need to close connection only before I exit application? I ask because in tutorials is told that the best option is to create connection with try-with-resources. But with try-with-resources or DatabaseConnection.getConnection().close I will close connection and I can't restore it later in application with singleton. Can you explain it to me?

Browse stack overflow and google but I didn't find answer

2

There are 2 answers

1
Rajan Kumar Sharma On

You are making connection inside the static block and static block gets loaded during class loading. So to close the connection you have to close the application.

And if you want to make singleton then create a class and make constructor private and inside that constructor define your database connection.

2
Roman C On

The singleton class is not a connection. The connection is a property of singleton class DatabaseConnection. If you close a connection then if you want to continue to work with DatabaseConnection then you should use a DriverManager.getConnection() again.