Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sharing a JDBC Connection object between other objects

I have created a Database class which uses a static connection object in order to be used in common between instances of itself. my question is that is there any problem with this approach or not?

class Database {
    private static Connection connection = null;

    public Database() {
        if(connection == null){
            ...
            connection = DriverManager.getConnection(...);
            ...
        }
    }
}
like image 854
jacksparrow92 Avatar asked May 17 '13 16:05

jacksparrow92


People also ask

Can JDBC share a single connection among multiple threads?

JDBC allows you to share a single Connectionamong multiple threads. Pitfalls of sharing a connection among threads Here is a review of the potential pitfalls of sharing a single Connection among multiple threads. Multi-thread programming tips

What is the JDBC connection tutorial?

This JDBC Connection tutorial explains basic steps to a database with examples and provides JDBC connection strings for different databases: In the previous tutorial of the JDBC tutorial series, we learned components, architecture, and types of drivers in Java Database Connectivity (JDBC).

How do I Close a JDBC connection in Java?

From Java 7 onwards, we can close the JDBC connections automatically using a try-catch block. JDBC connection should be opened in the parenthesis of the try block. Inside the try block, you can do the database connections normally as we do. Once the execution exits the try block, it will automatically close the connection.

How to send and receive data from database using JDBC?

Once a connection is established you can interact with the database. The JDBCStatement, CallableStatement, and PreparedStatement interfaces define the methods that enable you to send SQL commands and receive data from your database. Use of JDBC Statement is as follows: Statement st = con.createStatement ();


2 Answers

If you are going to have many (hundreds) of queries per second then implementing a connection pool is the way to go. See the answer to this question for more details. However, if you a Java novice (we all were one day!) then I don't imagine you will be needing this requirement, and probably will struggle to implement it.

Instead, the simple pattern of creating a new connection if required, and then closing it when finished will be the best way to go forward for you. Below is a modified version of your Database class which I think is a good way to move forward.

class Database {
    private Connection con = null;
    private final String connectionString;

    public Database(String connectionString) {
        this.connectionString = connectionString;
    }

    public void connect() throws SQLException {
        if (con != null // if the connection exists
             && !con.isClosed() // and has not been closed 
             && con.isValid(0)) { // and appears to be functioning (with a test timeout of 0ms)
             return; // skip connection creation
        }

        // create the connection
        con = DriverManager.getConnection(connectionString);        
    }

    public void testFunction() {
        try {
            connect();
            // .. do some stuff with the connection ..
        } catch (Exception e) {
            // log or otherwise deal with the error
        } finally {
            try {
                con.close();
            } catch (Exception e) {
                System.err.println("Failed to close connection: " + e.toString());
            }
        }

    }
}

Some things to note about this solution:

  • It is not very efficient - creating a new connection always takes more time than using an existing one
  • This class if not thread safe - if you need this requirement, I recommend using a thread pool. However, if you create a new instance of this class per thread then it will be thread safe (as there is not static connection to worry about!)
  • It does do the job - certainly for simple cases. I use the model for a relatively low volume database which has approx 50-100 connections made/closed per minute and it does not add a noticeable lag
  • It is very robust - nothing is safer than opening and closing a connection per query. You are guaranteed to be able to handle a connection failure per query, and the connection will always be closed (unless it already has been).

Disclaimer The solution above is not a particularly amazing solution. However, I believe it is simple to implement and a good way for a Java novice to get to know the ropes before jumping into external libraries.

like image 125
Overlord_Dave Avatar answered Sep 22 '22 06:09

Overlord_Dave


There is nothing wrong with creating an object to manage your connections, however, connections should be opened and closed and can be used in multi-threaded environments, so having a static connection is not a good idea. For a method that needs a connection, get a connection use it, close it. Even if you are not using it in a multi-threaded environment, the connection can time-out, then you need to constantly check if the connection is up and available, instead of just saying, get me a connection, use the connection, close it.

like image 34
user1209809 Avatar answered Sep 25 '22 06:09

user1209809