在Jar内部打包并使用嵌入式数据库(H2.db文件)? [英] Package and use embedded database (H2.db file) inside a Jar?

查看:944
本文介绍了在Jar内部打包并使用嵌入式数据库(H2.db文件)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的应用程序使用H2嵌入式数据库。我想在其自己的Jar中包含应用程序所需的所有内容,如果可能的话,包括它的数据库。我的应用程序不需要创建临时文件或任何东西,所以基本上用户只运行Jar。

I'm using H2 embedded database for my application. I would like to contain everything the application needs in it's own Jar, including it's database if possible. My app does not need to create temp files or anything, so basically the user just runs the Jar.

是否可以在Jar中嵌入数据库,并能够 INSERT 新记录以及 SELECT out?

Is it possible to embed a database inside a Jar, and be able to INSERT new records as well as just SELECT out?

编辑:为了澄清,我不打算在我的可分发jar中嵌入H2驱动程序jar,我想嵌入h2数据库文件( someDatabase。一个Jar内部的h2.db 文件)仍然可以从该数据库中写入/读取。

Just to clarify, I'm not looking to embed the H2 driver jar inside my distributable jar, I'm looking to embed the h2 database file (someDatabase.h2.db file) inside a Jar and still be able to write/read from that database.

推荐答案

如果你想在 .jar 中嵌入 myDatabase.h2.db 文件,你可以这样做,但是你将拥有对数据库的只读权限。由于 .jar 文件是只读的,因此无法修改它们,因此无法执行 INSERT DELETE 或任何DDL命令。

If you wish to embed the myDatabase.h2.db file inside the .jar, you can do so, but you'll have read-only access to the database. As .jar files are read-only, you can't modify them and therefore can't execute INSERT, DELETE or any DDL command.

话虽如此,下面是如何将其嵌入只读的说明。

That being said, below is an explanation on how to embed it read-only.

根据 H2的文档

JDBC URL jdbc:h2:〜/ myDatabase告诉H2引擎寻找当前用户的主目录中名为 myDatabase.h2.db 的数据库文件。

The JDBC URL "jdbc:h2:~/myDatabase" tells the H2 Engine to look for a database file named myDatabase.h2.db in the home directory of the current user.

JDBC URL jdbc:h2:file:/ myDatabase告诉H2引擎查找名为 myDatabase.h2的数据库文件。 当前目录中的db (执行java程序的地方)。

The JDBC URL "jdbc:h2:file:/myDatabase" tells the H2 Engine to look for a database file named myDatabase.h2.db in the current directory (where the java program was executed).

如果嵌入 h2.db .jar 中的文件,无法以简单的方式访问它。它只能作为zip文件中的文件访问。

If you embed the h2.db file inside a .jar, it is not accessible in a plain way. It is only accessible as a file inside a zip file.

为了使H2使用它,你必须使用zip作为URL:

In order to make H2 uset it, you have to use a zip as URL:

jdbc:h2:zip:~/data.zip!/test

Zip或Jar文件中的只读数据库中查看更多内容

当您将文件作为资源嵌入jar中时,您可能会得到它的相对URL。使用...

When you embed the file as a resource in the jar, you may get it's relative url. Using...

MyClass.class.getClassLoader()。getResource(myDatabase.h2.db)

...你会得到类似的东西:

...you'll get something like:

jar:file: /C:/folder1/folder2/myJar.jar!/myDatabase.h2.db

然后,您可以将其作为字符串进行操作并传递作为与H2的JDBC URL连接。

You can then manipulate it as a String and pass as JDBC URL connection to H2.

这篇关于在Jar内部打包并使用嵌入式数据库(H2.db文件)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆