oracle jdbc 重连
时间: 2023-06-28 11:05:02 浏览: 69
在使用 Oracle JDBC 连接数据库时,如果连接中断了,可以通过以下步骤进行重连:
1. 在连接中断后,捕获 SQLException 异常。
2. 判断异常信息是否为连接中断或者超时错误。
3. 如果是连接中断或者超时错误,关闭原来的连接,重新建立新的连接。
下面是一个示例代码:
```
Connection conn = null;
Statement stmt = null;
try {
// 尝试连接数据库
conn = DriverManager.getConnection(url, user, password);
// 执行 SQL 语句
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
// 处理结果集
// ...
} catch (SQLException e) {
if (e.getErrorCode() == 17002 || e.getErrorCode() == 08003) {
// 连接中断或者超时错误
try {
// 关闭原来的连接
conn.close();
} catch (SQLException e1) {
// 忽略关闭连接时的异常
}
// 重新建立新的连接
conn = DriverManager.getConnection(url, user, password);
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
// 处理结果集
// ...
} else {
// 其他错误,抛出异常
throw e;
}
} finally {
// 关闭资源
try {
if (stmt != null) {
stmt.close();
}
} catch (SQLException e) {
// 忽略关闭 Statement 时的异常
}
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
// 忽略关闭连接时的异常
}
}
```
注意,这里只处理了连接中断或者超时错误,其他错误仍然会抛出异常。另外,关闭连接和 Statement 时也可能会抛出异常,需要进行处理。