日期:2014-05-17  浏览次数:20701 次

关于java中使用jdbc连接数据库的问题
用jdbc连接一个sqlserver数据库,如果连接失败则间隔五秒后继续尝试连接,尝试连接三次仍然失败后报错。各位大神求帮助啊,希望能给个大概思路,最好给做个例子。谢谢了
jdbc

------解决方案--------------------
多次尝试连接,时间间隔可以用Thread.sleep(5000) 控制。
------解决方案--------------------
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;

protected void getCon(){
String url = GetJdbc.getInstance().getProperty("url");
String userName = GetJdbc.getInstance().getProperty("userName");
String password = GetJdbc.getInstance().getProperty("password");
while(true){
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(url, userName, password);
if(con!=null)
  {
  return break;
   }
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
System.out.println("数据库连接失败");
 }

}

------解决方案--------------------
定义一个static的state标识,直接catch Exception然后再调用自己,可以设置成功返回connection,执行一次state++,判断state>3,直接return null
------解决方案--------------------
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;

protected void getCon(){
String url = GetJdbc.getInstance().getProperty("url");
String userName = GetJdbc.getInstance().getProperty("userName");
String password = GetJdbc.getInstance().getProperty("password");
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Object ob =new Object();
int count=0;
while (count<3)
{
  con = DriverManager.getConnection(url, userName, password);
  if(con!=null)
  {
    break;
   }else
  {
   
     synchronized(ob)
     {
      ob.wait(5000);
      }
  }
}

} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}

}