Embedding the Java h2 database programmatically

↘锁芯ラ 提交于 2019-11-27 03:40:14

From the download, I see that the file tutorial.html has this

import org.h2.tools.Server;
...
// start the TCP Server
Server server = Server.createTcpServer(args).start();
...
// stop the TCP Server
server.stop();
Alex Miller

Yes, you can run H2 in embedded mode. You just use the JDBC driver and connect to an embedded url like this (their example):

This database can be used in embedded mode, or in server mode. To use it in embedded mode, you need to:

* Add h2.jar to the classpath
* Use the JDBC driver class: org.h2.Driver
* The database URL jdbc:h2:~/test opens the database 'test' in your user home directory

Example of connecting with JDBC to an embedded H2 database (adapted from http://www.h2database.com/javadoc/org/h2/jdbcx/JdbcDataSource.html ):

import org.h2.jdbcx.JdbcDataSource;
// ...
JdbcDataSource ds = new JdbcDataSource();
ds.setURL("jdbc:h2:˜/test");
ds.setUser("sa");
ds.setPassword("sa");
Connection conn = ds.getConnection();

If you're looking to use H2 in a purely in-memory / embedded mode, you can do that too. See this link for more:

You just need to use a special URL in normal JDBC code like "jdbc:h2:mem:db1".

If for some reason you need an embedded H2 database in server mode you can do it either manually using the API at http://www.h2database.com/javadoc/org/h2/tools/Server.html - or by appending ;AUTO_SERVER=TRUE to the database URL.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!