Search code examples
javadatabase-connectionderbyjavadb

How to check if another instance of Derby is already booted?


I'm writing some Java application that uses Java DB (i.e. Apache Derby) as database. I use the following method to connect to database:

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;            
    }

This works ok, but sometimes I get the following exception:

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

This happens when I run my application and at the same time SQuirreL SQL Client is connected to my database. So everything works as expected, but I would like to be able to check for this in my getConnection() method. I other words, I would like to check if any sessions are opened to my database, and for example, close them, throw my own exception or display error dialog box. I don't know how to do this.

Thx


Solution

  • Rather than declaring that your application "throws SQLException", you can use a "try" block to catch the SQLException, then examine the exception and decide if it is the "Another instance of Derby" exception or not.

    Then, you can throw your own exception from your "getConnection" method accordingly.