简体   繁体   English

如何在运行时备份嵌入式 H2 数据库引擎?

[英]How to back up the embedded H2 database engine while it is running?

I would like to build up an web application with H2 database engine.我想用 H2 数据库引擎构建一个 Web 应用程序。 However, I still don't know how to back up the data while the database is running after reading this tutorial:但是,读了这篇教程后,我仍然不知道如何在数据库运行时备份数据:

http://www.h2database.com/html/tutorial.html#upgrade_backup_restore http://www.h2database.com/html/tutorial.html#upgrade_backup_restore

Does H2 output its stored file to somewhere in the file system? H2 是否将其存储的文件输出到文件系统中的某个位置? Can I just back up the outputted files?我可以只备份输出的文件吗?

H2 is stored on the file system, but it would be better to use the backup tools that you reference, because the file format can change between versions of H2. H2 存储在文件系统上,但最好使用您引用的备份工具,因为文件格式可能会在 H2 版本之间发生变化。 If you upgrade H2, it may not any longer be able to read the files it created in a previous version.如果升级 H2,它可能不再能够读取它在以前版本中创建的文件。 Also, if you copy the files it uses, I would recommend shutting the database down first, otherwise the copied files may be unreadable by H2.此外,如果您复制它使用的文件,我建议先关闭数据库,否则 H2 可能无法读取复制的文件。

The location of the file depends on the jdbc url you specify.文件的位置取决于您指定的 jdbc url。 See the FAQ: http://www.h2database.com/html/faq.html请参阅常见问题解答: http : //www.h2database.com/html/faq.html

As per the tutorial you linked , it is not recommended to backup the database by copying the files while it is running.根据您链接教程,不建议在数据库运行时通过复制文件来备份数据库。 Here is the right way to backup the database while it is running (Scala code, but can be easily converted to Java) ( Source ):这是在运行时备份数据库的正确方法(Scala 代码,但可以轻松转换为 Java)( ):

val connection:java.sql.Connection = ??? // get a database connection 
connection.prepareStatement("BACKUP TO 'myFile.zip'").executeUpdate 

Thx to Jus12 for the nice answer.感谢 Jus12 获得了不错的答案。 I adapted it for JPARepositories in Spring Data and would like to share it here as I couldn't find a similar answer online:我将它改编为 Spring Data 中的 JPARepositories 并想在这里分享它,因为我在网上找不到类似的答案:

@Modifying
@Transactional
@Query(value = "BACKUP TO ?1", nativeQuery = true)
int backupDB(String path);
 try{
     Class.forName("org.h2.Driver");
       Connection con = DriverManager.getConnection("jdbc:h2:"+"./Dbfolder/dbname", "username", "password" );
       Statement stmt = con.createStatement();
       con.prepareStatement("BACKUP TO 'backup.zip'").executeUpdate();

        }catch(Exception ex){
            JOptionPane.showMessageDialog(null, ex.toString());
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM