Java 如何检查Derby的另一个实例是否已经启动?
我正在编写一些使用JavaDB(即ApacheDerby)作为数据库的Java应用程序。我使用以下方法连接到数据库:Java 如何检查Derby的另一个实例是否已经启动?,java,database-connection,derby,javadb,Java,Database Connection,Derby,Javadb,我正在编写一些使用JavaDB(即ApacheDerby)作为数据库的Java应用程序。我使用以下方法连接到数据库: Connection getConnection() throws SQLException { EmbeddedDataSource ds = new EmbeddedDataSource(); ds.setDatabaseName(dbUri); ds.setPassword(password); ds.s
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
当我运行我的应用程序,同时SquirrelSQL客户端连接到我的数据库时,就会发生这种情况。所以一切都按预期进行,但我希望能够在我的getConnection()
方法中检查这一点。换句话说,我想检查是否有任何会话打开到我的数据库,例如,关闭它们,抛出我自己的异常或显示错误对话框。我不知道怎么做
Thx您可以使用“try”块捕获SQLException,然后检查异常并确定它是否是“Derby的另一个实例”异常,而不是声明应用程序“抛出SQLException”
然后,您可以相应地从“getConnection”方法抛出自己的异常。我将我的
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;
}
预防胜于治疗。在我看来,捕获异常然后实现它是重复的Derby服务器启动并不是一个理想的设计。最好是防止重复实例化。如果可能,您可以同步您的
getConnection()
方法,或者使其成为单例类的一部分,或者从JVM只加载一次的启动/主类的静态初始值设定项块加载嵌入式Derby驱动程序,因此Derby将只启动一次。在main/startup类中,类似于以下内容的内容应该可以做到这一点:
static {
try {
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
}
catch(Exception e){
.....
}
}
根据此处的链接,加载驱动程序应启动Derby嵌入式系统