0

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;
    }
3
Contributors
3
Replies
4
Views
5 Years
Discussion Span
Last Post by SRocks
0

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.

0

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.

0

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.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.