Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connection Retry using JDBC

Tags:

java

jdbc

I am using JDBC to connect to a DB. Since the network was slow, i could get the connection after some 2 or 3 retry manually. Is it possible to retry the connection automatically if connection fails? I am using SQLServer 2008 database. Thanks

like image 522
Manoj Avatar asked Dec 04 '22 08:12

Manoj


1 Answers

A bit decent connection pool is already configureable to do so, for example BoneCP. Most do even do it by default. If you don't use a connection pool but just the basic DriverManager#getConnection() approach, then you have to re-execute it yourself in a while loop as long as the Connection is null.

Here's a basic kickoff example:

Connection connection = null;

while (connection == null) {
    try {
        connection = DriverManager.getConnection(url, username, password);
    } catch (SQLException e) {
        logger.info("Connecting failed, retrying...");
    }
}

return connection;

This can of course be optimized more with bit longer pauses in between and by setting a maximum retry count, etcetera.

like image 100
BalusC Avatar answered Dec 06 '22 11:12

BalusC