如果DB没有响应,如何抛出超时异常?
我从DB2获取行,有时连接数据库需要很长时间。
如果连接超过1分钟,我想抛出异常。我在我的代码中使用预准备语句。
答案 0 :(得分:0)
尝试使用Drivermanager
方法设置setLoginTimeout
的超时设置:
DriverManger.setLoginTimeout(1000);
Connection c = DriverManger.getConnection(url, username, password);
如果连接无法在指定的时间内以毫秒为单位打开,则getConnecton
调用应该超时。
答案 1 :(得分:0)
您需要java.util.Timer
类并将计时器设置为1分钟然后开始合并。
如果您及时获得连接,则取消计时器或向用户显示该消息。
以下是代码示例。
public class TimerSample {
public static void main(String[] args) {
//1- Taking an instance of Timer class.
Timer timer = new Timer("Printer");
//2- Taking an instance of class contains your repeated method.
MyTask t = new MyTask();
//TimerTask is a class implements Runnable interface so
//You have to override run method with your certain code black
//Second Parameter is the specified the Starting Time for your timer in
//MilliSeconds or Date
//Third Parameter is the specified the Period between consecutive
//calling for the method.
timer.schedule(t, 0, 2000);
}
}
class MyTask extends TimerTask {
//times member represent calling times.
private int times = 0;
public void run() {
times++;
if (times <= 5) {
System.out.println("I'm alive...");
} else {
System.out.println("Timer stops now...");
//Stop Timer.
this.cancel();
}
}
}