Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
176 views
in Technique[技术] by (71.8m points)

Embedding the Java h2 database programmatically

At the moment we use HSQLDB as an embedded database, but we search for a database with less memory footprint as the data volume grows.

Derby / JavaDB is not an option at the moment because it stores properties globally in the system properties. So we thought of h2.

While we used HSQLDB we created a Server-object, set the parameters and started it. This is described here (and given as example in the class org.hsqldb.test.TestBase).

The question is: Can this be done analogous with the h2 database, too? Do you have any code samples for that? Scanning the h2-page, I did not find an example.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...