I’m using singleton design-pattern for my database connection.
Here is my method.
private static Connection con=null;
public static Connection getConnection(){
try {
if(con==null){
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection("jdbc:mysql://localhost/mydb", "root", "");
}else if(con.isClosed()){
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection("jdbc:mysql://localhost/mydb", "root", "");
}
} catch (Exception ex) {
}
return con;
}
Whenever I restarted mysql service, it generates following error and have to restart the application also to run again.
Error:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException:
Communications link failure
Can anyone show what is the correct way of implementing this to avoid this error?
thank you.
You’re reusing the same
Connectionobject across… well, everything. Your singleton should be aConnectionFactorythat returns a new connection every time.As someone already noted, rather than create/close new connections use a connection pool. You don’t have to write it yourself—there are readily available open-source implementations such as C3PO or DBCP.
Even better, rather than reinventing this wheel all over again, use a
DataSource. If you can use Spring, it has aDriverManagerDataSourceimplementation just for this. Otherwise, feel free to look at how it’s written and write your own (I’ve done this at least once when Spring wasn’t an ‘allowed’ technology).Finally, if you’re running in a container such as Tomcat, JBoss or Glassfish, then you can simply bind a
DataSourceto JNDI and use that. This frees up your application from having to handle pooling and configuration/deployment issues (stuff like database user name & password) itself.