【问题标题】:How to check if another instance of Derby is already booted?如何检查另一个 Derby 实例是否已经启动?
【发布时间】:2013-02-04 10:59:29
【问题描述】:

我正在编写一些使用 Java DB(即 Apache Derby)作为数据库的 Java 应用程序。我使用以下方法连接数据库:

Connection getConnection() throws SQLException {

        EmbeddedDataSource  ds =  new EmbeddedDataSource();
        ds.setDatabaseName(dbUri);
        ds.setPassword(password);
        ds.setUser(username);

        Connection conn = ds.getConnection();               
        conn.setSchema(schema); 

        return conn;            
    }

这工作正常,但有时我得到以下异常:

java.sql.SQLException: Another instance of Derby may have already booted the database

当我运行我的应用程序并且同时 SQuirreL SQL 客户端 连接到我的数据库时会发生这种情况。所以一切都按预期工作,但我希望能够在我的 getConnection() 方法中检查这一点。换句话说,我想检查是否有任何会话打开到我的数据库,例如,关闭它们、抛出我自己的异常或显示错误对话框。我不知道该怎么做。

谢谢

【问题讨论】:

    标签: java database-connection derby javadb


    【解决方案1】:

    您可以使用“try”块来捕获 SQLException,然后检查异常并确定它是否是“Another instance of Derby”异常,而不是声明您的应用程序“抛出 SQLException”。

    然后,您可以相应地从“getConnection”方法中抛出您自己的异常。

    【讨论】:

      【解决方案2】:

      我将getConnection() 方法修改为如下所示。它做我想要的:

        Connection getConnection() throws SQLException, DAOConnection {
      
              EmbeddedDataSource  ds =  new EmbeddedDataSource();
              ds.setDatabaseName(dbUri);
              ds.setPassword(password);
              ds.setUser(username);
      
              Connection conn = null;
      
              try {
                  conn = ds.getConnection();
              } catch (SQLException e) {          
      
                  // check if cannot connect due to "Another instance of 
                          // Derby may have already booted the database".
                          // The error code of this exception is 45000.
      
                  if (e.getNextException().getErrorCode() ==  45000) {
                      throw new DAOConnection(e.getNextException().getMessage());
                  } 
      
                  throw new SQLException(e);
              }
      
              conn.setSchema(schema);                         
              return conn;            
          }
      

      【讨论】:

        【解决方案3】:

        预防胜于治疗。 IMO,捕获异常然后意识到它是重复的 Derby 服务器启动并不是一个理想的设计。最好是防止重复实例化。如果可能的话,您可以同步您的 getConnection() 方法或使其成为 单例类 的一部分,或从启动/主类的 静态初始化块 加载嵌入式 Derby 驱动程序,该类是JVM 仅加载一次,因此 Derby 将仅启动一次。在 main/startup 类中进行如下操作应该可以解决问题:

        static {
           try {
                Class.forName("org.apache.derby.jdbc.EmbeddedDriver"); 
           }
           catch(Exception e){
            .....
           }
        }
        

        根据此处的链接http://db.apache.org/derby/docs/10.3/devguide/tdevdvlp38381.html 加载驱动程序应该会启动 Derby 嵌入式系统。

        【讨论】:

          猜你喜欢
          • 2014-05-27
          • 1970-01-01
          • 2014-03-30
          • 1970-01-01
          • 2017-12-06
          • 2016-03-31
          • 1970-01-01
          • 1970-01-01
          • 2019-12-25
          相关资源
          最近更新 更多