try {
EmbeddedDataSource40 ds = new
EmbeddedDataSource40();
ds.setDatabaseName(storageDirectory.getAbsolutePath());
ds.setCreateDatabase("create");
Connection connection = ds.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
EmbeddedDataSource40 is the class for the JDBC 4.0 of Java 6. For older Java versions there is also the class EmbeddedDataSource.
The line ds.setCreateDatabase("create"); is optional. It just lets derby create the database when it doesn't exists.
To shutdown the database replace the ds.setCreateDatabase("create"); with ds.setShutdownDatabase("shutdown");. It should look like this:
try {
EmbeddedDataSource40 ds = new
EmbeddedDataSource40();
ds.setDatabaseName(f.getAbsolutePath());
ds.setShutdownDatabase("shutdown");
ds.getConnection();
throw new
RuntimeException("Database didn't shut down.");
} catch (SQLException e) {
if (!"08006".equals(e.getSQLState())) {
throw new RuntimeException("Shutdown
of db failed.",e);
}
}
The ds.getConnection() is causing the shutdown. As stated in the derby docs this method will not return but throw an SQLException on success. When there is an error there should also be an exception but just to get save I've placed the throwing of a RuntimeException at the end of the block.
In the catch block for the SQLException you need to check the SQLState as there are only two legal values for shutdown. "08006" for shutting down a single database and "XJ015" for shutting down the whole database system.