How to make a thread try to reconnect to the Database x times using JDBCTemplate

Posted by gillJ on Stack Overflow See other posts from Stack Overflow or by gillJ
Published on 2010-05-19T14:46:35Z Indexed on 2010/05/19 14:50 UTC
Read the original article Hit count: 285

Filed under:
|
|

Hi,

I have a single thread trying to connect to a database using JDBCTemplate as follows:

    JDBCTemplate jdbcTemplate =  new JdbcTemplate(dataSource); 

    try{
        jdbcTemplate.execute(new CallableStatementCreator() {
   @Override
   public CallableStatement createCallableStatement(Connection con)
     throws SQLException {
    return con.prepareCall(query);
   }
  }, new CallableStatementCallback() {
    @Override
    public Object doInCallableStatement(CallableStatement cs)
      throws SQLException {
     cs.setString(1, subscriberID);
     cs.execute();
     return null;
    }
   });
     } catch (DataAccessException dae) {
   throw new CougarFrameworkException(
     "Problem removing subscriber from events queue: "
       + subscriberID, dae);
  }

I want to make sure that if the above code throws DataAccessException or SQLException, the thread waits a few seconds and tries to re-connect, say 5 more times and then gives up. How can I achieve this? Also, if during execution the database goes down and comes up again, how can i ensure that my program recovers from this and continues running instead of throwing an exception and exiting?

© Stack Overflow or respective owner

Related posts about java

Related posts about jdbc