我正在尝试使用重试逻辑来获得JDBC连接,以防我得到SQL异常,例如:
int counter = 0;
Connection conn = null;
while (null == conn) {
try {
conn = GetConnectionObject;
} catch (SQLException e) {
if (++counter > MAX_RETRY) {
//Log ERROR
break;
}
} finally {
if (null != conn) {
try {
DbUtils.close(conn);
} catch (SQLException e) {
logger.error("Exception while closing the connection object");
}
}
}
}我目前无法测试这一点,因此需要一些帮助。
如果我得到异常,然后可以在重试后登录,这将很好。但是,如果我们没有异常,它将来到最后块并关闭连接。尝试-抓住-终于在里面,而循环。
所以,如果我关闭我的连接,流动如果到达
同时( null==康涅狄格州)
关闭后,我的连接对象会变成空吗?
或者是否有其他方法来实现重试部分?
发布于 2018-10-17 11:10:53
不,关闭后不会变成空的。使用Connection.isClosed()而不是while( null== conn)。另外,您应该将//Do some task.从这段代码中删除,因为它的目标是获得JDBC。
发布于 2018-10-17 12:02:40
这是针对您的问题的测试方法。该方法为连接尝试3次,当它获得DB连接时,它将打印成功消息并运行查询并显示结果,否则它将打印错误消息。另外,如果连接成功,那么它将在最后块中执行查询后关闭连接。
public void retryDBConnection(){
int counter = 0;
Connection con = null;
while(counter < 3 && con == null){
try{
String str = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
Class.forName(str).newInstance();
con = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;Database=TestDB;", "sa", "sqldb");
System.out.println("DB Connection Successful!");
PreparedStatement prep = con.prepareStatement("select ID, User_Name from tblUser where ID = 9");
ResultSet rs = prep.executeQuery();
if(rs.next()){
System.out.println("User ID = " + rs.getString(1));
//name = rs.getString(2);
}
}
catch(SQLException e){
// System.out.println(e.getSQLState());
if(e.getErrorCode() == 0 || e.getErrorCode() == 4060)
counter++;
System.out.println("Attempt: " + counter +", Could not establish DB Connection!");
System.out.println("Error Code: " + e.getErrorCode());
}
catch(Exception e){
e.printStackTrace();
}finally{
if(con != null){
try {
con.close();
System.out.println("Connection closed...");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}这是这个方法的输出。 尝试: 1,无法建立DB连接!错误代码:0尝试: 2,无法建立DB连接!错误代码: 4060 DB连接成功!用户ID =9连接关闭..。
https://stackoverflow.com/questions/52853209
复制相似问题