How can I use one database connection object in whole application?

Dhruv Kapatel picture Dhruv Kapatel · Dec 18, 2013 · Viewed 44.3k times · Source

I have created this class which returns connection object. I have used MySQL database.

public class Connect_db {        
    public Connection getConnection(String db_name,String user_name,String password)
    {
        Connection con=null;
        try
        {
        Class.forName("com.mysql.jdbc.Driver");
        con=DriverManager.getConnection("jdbc:mysql://localhost/"+db_name+"?user="+user_name+"&password="+password);
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

        return con;        
    }
}  

Now all I want to do is instantiate this class once and get connection object. And I want to use this same object in entire application. Another solution will also be appreciated.

Answer

Iłya Bursov picture Iłya Bursov · Dec 18, 2013

I suppose you need singleton pattern, here is quick example:

public class Connect_db {        
    static Connection con=null;
    public static Connection getConnection()
    {
        if (con != null) return con;
        // get db, user, pass from settings file
        return getConnection(db, user, pass);
    }

    private static Connection getConnection(String db_name,String user_name,String password)
    {
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            con=DriverManager.getConnection("jdbc:mysql://localhost/"+db_name+"?user="+user_name+"&password="+password);
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

        return con;        
    }
} 

then you will be able to use connection like this:

Connect_db.getConnection().somemethods();

but, you should think - how this will work in multi-threaded environment, when several threads are trying to make requests to database.