Michael
Michael

Reputation: 5062

H2: Restore a (in-memory) database from a backup file

H2 provides a BACKUP command that can be used from a SQL statetement and creates a backup file:

String url = "jdbc:h2:nioMemFS:atestdb";
try (Connection con = DriverManager.getConnection(url); 
       Statement s = con.createStatement()) {
   s.execute("CREATE TABLE test_table ( test_values VARCHAR(255) )");
   s.execute("INSERT INTO test_table (test_values) VALUES ('abc'), "
     + "('def'), ('hji')");
   s.execute("BACKUP TO 'backup.zip'");  // writes to backup.zip
}

This also works for in-memory databases (edit: it works with the nioMemFS file system but not with plain in-memory databases; see Oleg`s answer below). Is there also a command for restoring such a database file?

Thanks!

Upvotes: 0

Views: 2655

Answers (1)

Oleg
Oleg

Reputation: 6314

The BACKUP command shouldn't work for in-memory database, when I try I get DATABASE_IS_NOT_PERSISTENT error, if the backup command works for you, you're probably not using a persistent database.

You can use the SCRIPT and RUNSCRIPT to backup and restore respectively via creating and running an sql script from the database.

SCRIPT TO 'backup.sql';
RUNSCRIPT FROM 'backup.sql';

Upvotes: 2

Related Questions