简体   繁体   中英

Open H2 Database from Classpath

I've seen from the H2 documentation that you can open files on the classpath .

I've tried various URLs (eg jdbc:h2:classpath:/myDatabase ) when opening a connection, but none seem to find the resource - but when I try MyClass.class.getClassLoader().getResourceAsStream("myDatabase") it can find it it fine.

The database is on the classpath in src\\test\\resources .

Any ideas what I'm doing wrong?

You can locate the myDatabase file. When running locally and unpacked, eg from inside the IDE you can do:

URL res = MyClass.class.getResource("/myDatabase");
String url = "jdbc:h2:" + res.toString();

which will output the full resource path eg jdbc:h2:file:/home/.../classes/myDatabase

This won't work when you package your app as a JAR or WAR. In this case the myDatabase will be packaged inside a ZIP archive, to quote this post :

The main problem for both zipped databases and databases in the classpath is: you can't do real random access. You can only read from a stream. Random access is required, so it is simulated like this: When seek(pos) larger than current position, then a skip is made (which is basically a read). If the seek pos is smaller, then the stream is closed and re-opened. This is very slow.

ZIP support is read-only based on Advanced > Pluggable File System docs :

zip: read-only zip-file based file system. Format: zip:/zipFileName!/fileName.

You probably should supply the path to the myDatabase using command line arguments or system variable and keep it outside of packaged application.

this works for me... it creates the pher folder in the classpath and "pharmadatabase" is my database name. jdbc:h2:file:pher/~/pharmadatabase;

you can see the path below-

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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