We help IT Professionals succeed at work.
Get Started

Reliable way to check jdbc connection?

shepp_it
shepp_it asked
on
470 Views
Last Modified: 2013-11-23
Hello,

We have a program that runs daily. This program once a while returns a SQLException: connection reset, maybe due to network glitch or something. As a workaround, I created logic that checks connection prior to execution of SQL query, and if connection is lost then wait 30 seconds and reconnects.

I used an if statement with condition (connection == null) to see if connection is lost but I doesn't seem to be reliable way to check if connection is lost. (connection.isClosed()) wouldn't be a good practice either since isClosed() may return an exception if connection is lost.

So, my question is, what is the most reliable way to check if connection still exists?
//check if connection exists
        if(conn == null){
            Wait.waitFor(30); //wait for 30 seconds if connection is lost
            System.out.println("waited 30 seconds!");
            
            db.OpenDB();
            conn = db.Con;
            
            try{
                if(conn.isClosed()){
                    System.out.println("Error at CheckConnection(Connection): Establishing connection attempted but still closed");
                }else{
                    System.out.println("Connection re-established");
                }
            }catch(SQLException e){
                System.out.println("Error at CheckConnection(Connection): Connection still lost even after attempting re-establishing connection");
            }
        }

        //check if connection is closed
        try{
            if(conn.isClosed()){
                System.out.println("Connection closed. Creating a new connection...");
                db.OpenDB();
                conn = db.Con;
            }
        }catch(SQLException e){
            System.out.println("Error at CheckConnection(Connection): Connection still lost");
        }

Open in new window

Comment
Watch Question
CERTIFIED EXPERT
Distinguished Expert 2020
Commented:
This problem has been solved!
Unlock 1 Answer and 3 Comments.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE