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
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.