简体   繁体   中英

Connection Retry using 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

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.

Here the code by which it re-try it 3 times to connect,you can also change the cont instead of 3 this can be changed to any number of times(5,10 etc)

 Connection connection = null;
          while (connection == null && count<3){
            try {

                  String Connection="jdbc:sqlserver://"+serverip+';'+"database="+dbName+';'+"user=" +Username+';'+"password=" +Password;
                  Class.forName(classname); 
                  connection = DriverManager.getConnection(Connection); 

                }catch (SQLException e){
                    count++;
                    System.err.println("Connecting failed, retrying...");
            }
          }
          count=0;  
          return connection;                  
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM