0

I have a main class, a login class and a gui class.

Within my main I am creating a database connection using the Singleton pattern - only one instance of this connection.

I want to access the database connection from login, to verify users upon logging into the system.

My connection method within main:

/**
 * Use the Singleton pattern to create one Connection
 */
private static Connection getConnection() {
    if (conn != null) {
        return conn;
    }
    try {
        Class.forName(driver);
    } catch (ClassNotFoundException e) {
        System.out.println(e.getMessage() + " load driver error");
        System.exit(0);
    }
    try {
        //conn = DriverManager.getConnection(host);
        conn = DriverManager.getConnection(host + "create=true", dbUsername, dbPassword);
    } catch (SQLException e) {
        displayErr("Get connection error: ", e);
        System.exit(0);
    }
    return conn;
}

Now, I want to create a login method where I need to use the connection conn. The method is static and I cannot use conn.

I'm sure this is wrong but I've also tried making a public method which returns the connection conn and then tried calling that method from Main.

conn = Main.returnConnection();

What should I do in this situation? Pretty confused at how I'm supposed to model this.

John Vasiliou
  • 977
  • 7
  • 27
  • 48

2 Answers2

1

Your approach is so primitive when it's compared with Connection Pooling. Connection pool means a pool that includes cached, reusable connections those can be used in future requests. As you said opening a connection for each user is an expensive process also giving a static connection for each user occurs conflictions. Connection pooling is the standart that should be used in these kind of circumstances.

connection = connectionPool.getConnection();

Upper code means get a connection from the pool, if all connections are already allocated, mechanism automatically creates a new one.

The most popular libraries are:

Ömer Faruk Almalı
  • 3,792
  • 6
  • 37
  • 63
0

I figured out the purpose of the Singleton pattern is to create one instance of something and allow it to be seen by everyone.

So I made it public static void instead and can now access the connection, without making a new one each time.

Correct me if I am wrong but this works fine.

John Vasiliou
  • 977
  • 7
  • 27
  • 48