shepp_it
asked on
Reliable way to check jdbc connection?
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?
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");
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Thanks for accepting, glad I was of help.
ASKER