-2

DB没有响应时如何抛出超时异常?

我正在从 DB2 获取行,有时连接数据库需要很长时间。

如果连接时间超过 1 分钟,我想抛出异常。我在我的代码中使用准备好的语句。

4

2 回答 2

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();
        }
    }
}
于 2013-09-24T07:17:05.127 回答
0

Drivermanager尝试在usingsetLoginTimeout方法上设置超时时间:

 DriverManger.setLoginTimeout(1000);
 Connection c = DriverManger.getConnection(url, username, password);

如果连接无法在以毫秒为单位的指定时间内打开,则getConnecton调用应该超时。

于 2013-09-24T07:10:51.373 回答