Embedding HSQLDB

HSQLDB is a fast, small, and robust relational database management system (RDBMS) written in Java. HSQLDB provides both in-memory and disk-based database implementations. HYSQLDB is small enough that it can be embedded into an application with little effort and is currently in use by OpenOffice, Jboss, Jira, and Mathematica amongst other software applications.

Embeddinging HSQLDB is as simple as adding the hsqldb.jar to your class path. Once you have the class path set, load the HSQLDB driver, as you would for any JDBC driver.

[source:java]
Class.forName(“org.hsqldb.jdbcDriver”);
[/source]

After registering the driver, you can just connect to a HSQLDB as you would with any other JDBC compliant database engine. It is hard to believe, but this is all you have to do to embed a database into your Java-based application!

You can connect to HSQLDB in two fashions, as an in memory database or persisted file-based database.

As an in-memory database, your database and all it’s data exist only while your application is running. Once you restart your application, you will need to recreate the tables and insert records to rebuild the database. An in-memory database are useful only if you don’t care if you loss the data. To create an in-memory database connect using code like the following, you can replace database_name with with something that is applicable to your application.

[source:java]
String url = “jdbc:hsqldb:mem:database_name”;
String user = “sa”;
String password = “”;
Connection c = DriverManager.getConnection(url, user, password);
[/source]

If you want your data to be stored and persisted after your application has exited, then you will have HSQLDB write the data to a file on disk. To create a file-based database use a JDBC URL like the following where you replace the path to the database file with something that is appropriate to your application.

[source:java]
String url = “jdbc:hsqldb:file:/path/to/database/file”;
String user = “sa”;
String password = “”;
Connection c = DriverManager.getConnection(url, user, password);
[/source]

You can also use a relative path your user.dir system property to your database file. The user.dir property contains the directory form which your Java process starts.

Once you have a JDBC connection to HSQLDB you create tables and insert rows as you normally would in JDBC.

Technorati Tags: , , , , , , ,