问题描述
|
我正在使用JDBC连接到数据库。由于网络速度很慢,在手动重试2或3次后,我可以获得连接。如果连接失败,是否可以自动重试连接?我正在使用SQLServer 2008数据库。
谢谢
解决方法
像样的连接池已经可以进行配置,例如BoneCP。大多数甚至默认情况下也会这样做。如果您不使用连接池,而仅使用基本的“ 0”方法,那么只要“ 2”为“ 3”,就必须在“ 1”循环中重新执行它。
这是一个基本的启动示例:
Connection connection = null;
while (connection == null) {
try {
connection = DriverManager.getConnection(url,username,password);
} catch (SQLException e) {
logger.info(\"Connecting failed,retrying...\");
}
}
return connection;
当然,这可以通过设置较长的重试次数和设置最大重试次数等来进一步优化。
,在这里,它重试连接3次的代码,您也可以更改cont而不是3,可以将其更改为任意次数(5,10等)
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;
}