2013-02-04 114 views
0

我在写一些使用Java DB(即Apache Derby)作为数据库的Java应用程序。我用下面的方法来连接数据库:如何检查另一个Derby实例是否已经启动?

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()方法中检查这一点。换句话说,我想检查是否有任何会话向我的数据库打开,例如关闭它们,抛出我自己的异常或显示错误对话框。我不知道该怎么做。

THX

回答

0

而不是宣布你的应用程序“抛出的SQLException”,你可以使用一个“尝试”块捕获的SQLException,然后检查异常,并决定是否是“德比的另一个实例”异常或不。

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

0

我修改了我的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;    
    } 
0

预防胜于治疗。国际海事组织,捕捉异常,然后意识到它是重复的Derby服务器启动不是一个理想的设计。更好的办法是防止重复实例化。如果可能的话,您可以同步getConnection()方法或使其成为单例类的一部分或从加载嵌入式Derby驱动程序的启动/主类的静态初始化程序块,该类仅由JVM加载一次,因此Derby将仅启动一旦。喜欢的东西下面的主/启动类应该做的伎俩:

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

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

相关问题