与自动重新连接的JDBC连接

时间:2009-10-13 21:24:57

标签: java jdbc firebird jaybird

我正在使用JDBC连接到数据库服务器。 连接是通过无线网络进行的,有时可能很狡猾。 在连接丢失的那一刻,我需要关闭并重新启动应用程序。

有没有人有一些代码示例,我可以编写某种包装器来自动重新连接并重新运行最后一个查询?这样可以省去很多麻烦。

我只是不确定它应该如何/可以实施。 也许已经有了可用的东西?

3 个答案:

答案 0 :(得分:6)

即使您使用JDBC连接池提供的应用程序服务器或apache commons池,也值得编写重试逻辑。根据应用程序服务器的配置,应用程序服务器将清除所有池连接并重新创建一组新连接。这是一个示例:

Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
//
// How many times do you want to retry the transaction
// (or at least _getting_ a connection)?
//
int retryCount = 5;
boolean transactionCompleted = false;
do {

  try {
    conn = getConnection(); // assume getting this from a
    // javax.sql.DataSource, or the
    // java.sql.DriverManager

    retryCount = 0;
    stmt = conn.createStatement();
    String query = "Some sample SQL";
    rs = stmt.executeQuery(query);
    while (rs.next()) {
    }
    rs.close();
    rs = null;
    stmt.close();
    stmt = null;

    conn.close();
    conn = null;
    transactionCompleted = true;
  } catch (SQLException sqlEx) {
    //
    // The two SQL states that are 'retry-able' 
    // for a communications error.
    //
    // Only retry if the error was due to a stale connection,
    // communications problem 
    //
    String sqlState = sqlEx.getSQLState();
    if ("Substitute with Your DB documented sqlstate number for stale connection".equals(sqlState) ) {
      retryCount--;
    } else {
      retryCount = 0;
    }
  } finally {
    if (rs != null) {
      try {
        rs.close();
      } catch (SQLException sqlEx) {
        // log this
      }
    }
    if (stmt != null) {
      try {
        stmt.close();
      } catch (SQLException sqlEx) {
        // log this
      }
    }
    if (conn != null) {
      try {
        //
        // If we got here, and conn is not null, the
        // transaction should be rolled back, as not
        // all work has been done
        try {
          conn.rollback();
        } finally {

          conn.close();
        }
      } catch (SQLException sqlEx) {
        //
        // If we got an exception here, something
        // pretty serious is going on, so we better
        // pass it up the stack, rather than just
        // logging it. . .
        throw sqlEx;
      }
    }
  }
} while (!transactionCompleted && (retryCount > 0));

答案 1 :(得分:3)

让连接池为您处理此问题,其中许多可以验证连接。 DBCP具有testOnBorrow参数也是如此,该参数在使用之前强制对每个连接进行健全性检查。此参数的默认值为true,只需将validationQuery设置为非空字符串即可生效。所以设置validationQuery然后就去了!查看documentation

答案 2 :(得分:1)

查看Oracle的通用连接池(UCP)库。它们完全符合JDBC 4.0,并实现isValid()调用以检查连接是否存在。如果错误重新连接,则很容易进行此检查,然后运行查询。

Oracle UCP Download Page

虽然我知道你没有询问连接池,但你应该使用一个连接池,所以这将帮助你双重。