Question

I create and use a H2 database in-memory (no writing to storage) for demos and quick tests using this code in Java:

 Connection conn = DriverManager.getConnection( "jdbc:h2:mem:example_db" ) ;

This works the first time, but then the database seems to disappear, unavailable for further work. How can I make use of the same in-memory database over time?

Was it helpful?

Solution

Set DB_CLOSE_DELAY=-1

By default, an in-memory database in H2 is discarded after the connection closes.

To override this default behavior, set DB_CLOSE_DELAY to a negative one. You can do so either:

  • When making a connection with a JDBC path
  • By calling a SQL command

JDBC path

To keep the database in existence despite the connection closing, add an element to your JDBC path. The database will continue to live on in memory until your app exits. So you can make successive connections to the same continuing database.

Tip: Notice the SEMICOLON (not COLON) between the database name and this element.

Connection conn = 
    DriverManager.getConnection( 
        "jdbc:h2:mem:example_db;DB_CLOSE_DELAY=-1"  // Set `DB_CLOSE_DELAY` to `-1` to keep in-memory database in existence after connection closes.
    ) 
; 

If you want to explicitly call for the default behavior, set 0. For a number of seconds before discarding the database after the last connection closes, pass a positive integer ( >=1 ).

This feature is covered in the manual in the section on In-Memory Database in the last paragraph.

By default, closing the last connection to a database closes the database. For an in-memory database, this means the content is lost. To keep the database open, add ;DB_CLOSE_DELAY=-1 to the database URL. To keep the content of an in-memory database as long as the virtual machine is alive, use jdbc:h2:mem:test;DB_CLOSE_DELAY=-1.

SQL command

This setting can also be manipulated at runtime via the SET DB_CLOSE_DELAY command, passing an integer.

To quote that documentation:

SET DB_CLOSE_DELAY int

Sets the delay for closing a database if all connections are closed. The value -1 means the database is never closed until the close delay is set to some other value or SHUTDOWN is called. The value 0 means no delay (default; the database is closed if the last connection to it is closed). Values 1 and larger mean the number of seconds the database is left open after closing the last connection.

If the application exits normally or System.exit is called, the database is closed immediately, even if a delay is set.

Admin rights are required to execute this command, as it affects all connections. This command commits an open transaction in this connection. This setting is persistent. This setting can be appended to the database URL: jdbc:h2:test;DB_CLOSE_DELAY=-1

Example:

SET DB_CLOSE_DELAY -1

Licensed under: CC-BY-SA with attribution
Not affiliated with dba.stackexchange
scroll top