简体   繁体   English

在内存数据库中h2保持连接打开多长时间?

[英]in memory database h2 how long keep connection open?

I am testing currently a H2 DB in memory mode. 我正在测试内存模式下的H2 DB。 I set up a connection by 我建立了一个连接

h2Con = DriverManager.getConnection( 
                "jdbc:h2:mem:db1", "SA", "");

I want to some imports with dbunit and set up dbUnits db connection 我想用dbunit进行一些导入并设置dbUnits数据库连接

IDataBaseConnection dBUnitConnection = new DatabaseConnection(h2con);

and the imports which i want to query later 以及我想稍后查询的导入

So my question is, in memory mode, when can i close the connection? 所以我的问题是,在内存模式下,何时可以关闭连接? Normaly i do something like this Normaly我做这样的事情

try{
   //some sql query
}catch{
   //error handling
}finally{
    if(connection!=null)
        connection.close()
}

But in memory if the connection is closed i loose the data? 但是在内存中,如果连接关闭,我会丢失数据? So should it stay open until i end my program? 所以它应该保持开放,直到我结束我的程序?

Add DB_CLOSE_DELAY=-1 in URL 在URL中添加DB_CLOSE_DELAY=-1

From H2 documentation : 从H2 文档

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. 要使数据库保持打开状态,请将DB_CLOSE_DELAY = -1添加到数据库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. 要在虚拟机处于活动状态时保留内存数据库的内容,请使用jdbc:h2:mem:test; DB_CLOSE_DELAY = -1。

So you can configure H2 to keep in-memory database intact due to the lifetime of your JVM and then you can connect and disconnect to it as you wish. 因此,您可以配置H2以保持内存数据库的完整性,因为JVM的生命周期,然后您可以根据需要连接和断开连接。

So, this: 所以这:

JdbcDataSource ds = new org.h2.jdbcx.JdbcDataSource();
ds.setURL("jdbc:h2:mem:example_db_");
ds.setUser("scott");
ds.setPassword("tiger");

…becomes this: ......变成这个:

JdbcDataSource ds = new org.h2.jdbcx.JdbcDataSource();
ds.setURL("jdbc:h2:mem:example_db_;DB_CLOSE_DELAY=-1"); // ⬅ Add ‘delay’ element to URL.
ds.setUser("scott");
ds.setPassword("tiger");

In some situations, the database should not be closed in this case, for example because the database is still used at virtual machine shutdown (to store the shutdown process in the database for example). 在某些情况下,在这种情况下不应关闭数据库,例如,因为数据库仍在虚拟机关闭时使用(例如,将关闭进程存储在数据库中)。 For those cases, the automatic closing of the database can be disabled in the database URL. 对于这些情况,可以在数据库URL中禁用数据库的自动关闭。 The first connection (the one that is opening the database) needs to set the option in the database URL (it is not possible to change the setting afterwards). 第一个连接(打开数据库的连接)需要在数据库URL中设置选项(之后无法更改设置)。 The database URL to disable database closing on exit is: 在退出时禁用数据库关闭的数据库URL是:

String url = "jdbc:h2:~/test;DB_CLOSE_ON_EXIT=FALSE"; String url =“jdbc:h2:〜/ test; DB_CLOSE_ON_EXIT = FALSE”;

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

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