Hi,

I have created the following code to get connection object to Database(MySql in my case) using a static method. I wanna know whether it is a good practice or not? Will there be any problem like concurrent access?

Any information will be helpful.

public static Connection connection(){
        Connection conn = null;
        String userName = "abcd";
        String password = "abcd";
        String url = "jdbc:mysql://localhost/abcd";
        String driver="com.mysql.jdbc.Driver";
        try{
        Class.forName (driver);
        conn = DriverManager.getConnection (url, userName, password);
        System.out.println ("Database connection established");
        }

        catch(Exception e){
            e.printStackTrace();
        }
        return conn;
    }

Recommended Answers

I do foresee one problem, that is that that method is able to return a null value, while the code calling it might be expecting a valid Connection. might be better to throw an Exception.

also, if you're worried about having several Connections to the same DB at the same …

Jump to Post

All 3 Replies

I do foresee one problem, that is that that method is able to return a null value, while the code calling it might be expecting a valid Connection. might be better to throw an Exception.

also, if you're worried about having several Connections to the same DB at the same time, why not re-using the existing one? the singleton pattern can help you there.

Hi stultuske,

Thanks for your "null" value suggestion will surely implement it.

For your second concern, i wanna take an example of web applications where i guess its not possible to use a single connection object because multiple users would be accessing the database from different pages . I am concerned about exactly same condition.

Please correct me if i am not able to understand your suggestion.

Dont use singleton pattern if you want concurrent access (Another reason for not using singleton is it is hard to unit test with this pattern)

Use Factory pattern instead.

A singleton pattern ensures that you always get back the same instance of whatever type you are retrieving, whereas the factory pattern generally gives you a different instance of each type.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.20 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.