【问题标题】:Java-JDBC Need code to throw exception while DB is not respondingJava-JDBC 需要代码在 DB 没有响应时引发异常
【发布时间】:2013-09-29 06:40:42
【问题描述】:

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

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

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

【问题讨论】:

    标签: java jdbc db2


    【解决方案1】:

    您需要拥有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();
            }
        }
    }
    

    【讨论】:

      【解决方案2】:

      尝试使用setLoginTimeout方法设置Drivermanager的超时时间:

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

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

      【讨论】:

      • 您好,如何在此处添加上述代码: DBConnection dbconn = new DBConnection(configuration.getProperties() .getProperty("database.name"), configuration.getProperties() .getProperty("database.用户名"), dbPwd); boolean isConnected = dbconn.connect(); logger.debug("连接建立 = " + isConnected); if (isConnected) 连接 = dbconn.getConnection();
      猜你喜欢
      • 2010-11-15
      • 1970-01-01
      • 1970-01-01
      • 2015-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多