Java Quiz Player

Blog Post

Java DB as an In-Memory Database

Jun 15, 2013

This post is about using Java DB as an in-memory database.

1. Java DB

Java DB is a relational database management system that is based on the Java programming language and SQL. This is the Oracle release of the Apache Software Foundation's open source Derby project. Java DB is included in the Java SE 7 SDK.

A Java DB database can be used as an in-memory database.

2. Java DB In-Memory

An in-memory database (IMDB) resides completely in the main memory of a computer. It does not use the file system.

An in-memory database is useful:

3. Create, Use, Remove and Persist an In-Memory Java DB Database

3.1. Creating:

Create an in-memory database using a database connection URL. The URL syntax is jdbc:derby:subsubprotocol:databaseName[;attribute=value]*. For the in-memory option, the subsubprotocol value is memory. This is required.

The following Java code creates an in-memory database with the name testDB. The Connection object is used to create database objects and data. The code uses JDBC API and the Java DB database is created in Embedded mode.

	String driver = "org.apache.derby.jdbc.EmbeddedDriver";
	String connectionURL = "jdbc:derby:memory:testDB;create=true";
	Connection conn = DriverManager.getConnection(connectionURL);

3.2. Using:

Create a database table and insert a data row, using the connection object.

	String DDL = "CREATE TABLE test_table (" +
			"id INT NOT NULL, " +
			"name VARCHAR(20) NOT NULL, " +
			"PRIMARY KEY (id))";
	Statement stmnt = conn.createStatement();
	String DML = "INSERT INTO test_table VALUES (1, 'test data')";
	stmnt = conn.createStatement();

3.3. Removing:

Remove (drop) the database using a connection URL with the drop attribute.

First, shutdown the database; this step is optional. If used, specify the URL attribute with key/value shutdown=true.

Next, drop the database; this also shuts down the database. The URL attribute key/value drop=true is required.

	String connectionURL = "jdbc:derby:memory:testDB;drop=true";

Just, exiting the JVM (exiting a Java program or 'ij') also drops the in-memory database.

3.4. Persisting:

Java DB in-memory database can be persisted to file system, if required. A copy of the database is created using the Java DB online backup system stored procedure SYSCS_UTIL.SYSCS_BACKUP_DATABASE. The backup copy is later restored as an in-memory, or a regular file system database.

The following are the restore connection URLs example for the in-memory and the file system options, respectively:

Note that, to use the copy as a file system database, the URL jdbc:derby:backupDbPath, can also be used without the restoreFrom attribute.


5. References

Return to top


Comments are welcome. Please note that comments are moderated.
Email to: info(at)javaquizplayer(dot)com.