如何连接到只读可运行jar内的H2数据库文件? [英] How can I connect to read only H2 database file which is inside runnable jar?

查看:186
本文介绍了如何连接到只读可运行jar内的H2数据库文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要求使用create / insert语句创建一次数据库,然后使用只读数据库访问权限使其在 javafx runnable jar 中可用。

I've requirement to create database once with create/insert statements and then make it available inside javafx runnable jar with read only DB access.

我刚刚经历过H2数据库文档很多次并尝试使用 H2驱动程序版本1.4.196和1.4.192 实现此目的但我我想我错过了一些东西。

I just gone through H2 database document many time and tried to achieve this using H2 Driver version 1.4.196 and 1.4.192 but I think I'm missing something.

我可以连接而不将它包含在runnable jar中,只读内容也可以。但是我需要从jar本身访问它以防止来自外部人员的数据库访问。

我是否可以连接字符串或逻辑来连接只读的DB文件jar本身?

Can I've connection string or logic to connect read only DB file from jar itself ?

当然我需要更明确的实例来自这个。

Ofcourse I need more clear practical example from this, this and this.

我已经将压缩逻辑实现为这个,它在给定路径下工作正常。

I've implemented zipping logic as this and it works fine from given path.

但是当我在runnable jar中添加zip文件并通过以下代码访问它时:

But when I've added zip file in runnable jar and accessing it through following code:

DriverManager.getConnection (jdbc:h2:file:split:zip:./ test.zip!/ test);

然后它抛出异常:

线程main中的异常org.h2.jdbc.JdbcSQLException:IO异常:java.io.FileNotFoundException:。\ jar \\\\buzdirectory .zip(系统找不到指定的路径); listFiles zip:./ jar / res / buzdirectory.zip!/[90031-196]

如果我把完全合格的路径然后它运行良好:

If I put fully qualified path then it works well:

DriverManager.getConnection(jdbc:h2:file:split:zip:C:\\CoreJava \\\ \\ src \\\\\\\\\\\\\。!!/ test);

我在这里缺少从jar文件中访问它。

What I'm missing here to access it from jar file.

推荐答案

想想我们无法直接从可运行的JAR文件中打开数据库文件。要访问它应该是一个真正的文件,所以我们需要从JAR中提取它然后打开该副本。

I think we cannot open the database file directly from the runnable JAR file. To access it should be a "real" file, so we will need to extract it from the JAR and then open that copy.

例如,从中提取数据库将JAR放入临时文件:

For example, to extract the database from the JAR into a temporary file:

File dbFile = File.createTempFile("temp", ".zip");
dbFile.deleteOnExit();

java.nio.file.Files.copy(this.getClass().getResourceAsStream("/db/temp.zip"), 
        dbFile.toPath(), java.nio.file.StandardCopyOption.REPLACE_EXISTING);

StringBuffer connStr = new StringBuffer("jdbc:h2:file:split:zip:")
        .append(dbFile.getAbsolutePath()).append("!/temp");

Connection conn = DriverManager.getConnection(connStr.toString());
conn.close();
System.out.println("closed");

顺便说一下,这不是一个好办法。但是我们可以在某些特殊情况下使用这种方法。

By the way this is not preferable approach yet all. But we can use this kind of approach in some special cases.

这篇关于如何连接到只读可运行jar内的H2数据库文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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