简体   繁体   中英

Problem with singleton database connection

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 should go for connection-pooling.

Your mechanism won't work if mysql server drops your connection some how.

You're reusing the same Connection object across... well, everything. Your singleton should be a ConnectionFactory that 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 a DriverManagerDataSource implementation 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 DataSource to 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM