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
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 =
"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.
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:
SET DB_CLOSE_DELAY -1