在内存数据库h2中保持连接打开多长时间? [英] in memory database h2 how long keep connection open?
问题描述
我目前正在以内存模式测试H2 DB。
我通过以下方式建立连接
I am testing currently a H2 DB in memory mode. I set up a connection by
h2Con = DriverManager.getConnection(
"jdbc:h2:mem:db1", "SA", "");
我想使用dbunit进行一些导入并设置dbUnits db连接
I want to some imports with dbunit and set up dbUnits db connection
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
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?
推荐答案
添加 DB_CLOSE_DELAY = -1 $ URL中的c $ c>
来自H2 文档:
默认情况下,关闭与数据库的最后一个连接会关闭
数据库。对于内存数据库,这意味着内容丢失。
要保持数据库打开,请在数据库URL中添加; DB_CLOSE_DELAY = -1。
要在虚拟
计算机处于活动状态时保留内存数据库的内容,请使用jdbc:h2:mem:test; DB_CLOSE_DELAY = -1。
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.
因此,由于JVM的生命周期,您可以配置H2以保持内存数据库完整,然后可以根据需要连接和断开连接。
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.
因此,这:
JdbcDataSource ds = new org.h2.jdbcx.JdbcDataSource();
ds.setURL("jdbc:h2:mem:example_db_");
ds.setUser("scott");
ds.setPassword("tiger");
...变成这样:
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");
这篇关于在内存数据库h2中保持连接打开多长时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!