Search code examples
javaderbyjavadb

How to overwrite a Java DB?


My app uses an embedded Java DB. A similar question asks how to create a Java DB if the target database does not already exist; adding the create=true attribute yields the desired result, e.g.:

     conn = DriverManager.getConnection("jdbc:derby:mydatabase;create=true",props);

But I would like to overwrite the database if it exists. I suppose I could simply delete and recreate the database's parent directory. Is there a better solution?


Solution

  • An embedded Derby database is entirely contained in the database's folder on the filesystem, so deleting that folder and recreating the database with create=true will be perfectly fine.

    It will also be perfectly fine to issue DROP TABLE and CREATE TABLE statements for all of the tables (and indexes, views, etc.) in your database.

    Both approaches accomplish the result. Which one is a "better solution" for your application is really up to you.

    In my applications, I tend to separate the table/index/view/constraint DDL statements from the application logic proper, and I also tend to have those collections of DDL statements be idempotent; that is, those DDL statements always start by dropping the previous table/view/index/etc. objects, then create the new ones, so I can run these DDL statements at any time during application development to recreate my database objects from scratch.

    But your application may not be structured like that, in which case maybe you will find it easier to physically remove the entire directory folder.