如何在可执行的Jar中包含SQLite数据库? [英] How to include SQLite database in executable Jar?
问题描述
我创建了一个使用SQLite作为本地数据库的Swing应用程序。数据库文件位于项目的根目录中。
I have created a Swing application that uses SQLite as a local database. The database file is located in project's root directory.
Project/DatabaseFile
应用程序在Eclipse上运行正常,但是当我运行打包的可执行文件Jar时,我收到以下错误:
The application runs fine on Eclipse, but when I run the packaged executable Jar, I get the following error:
No such table : table1
这意味着数据库无法访问。当我检查生成的JAR文件的内容时,数据库文件不再存在。
This means that the database is not reachable. When I examined the contents of the resulting JAR file, the database file was not there anymore.
在代码中,我按如下方式链接数据库:
In the code, I've linked the database as follows:
jdbc:sqlite:DatabaseFile
我的问题是,如何将SQLite数据库包含在可执行文件Jar中?
My question is, how to include the SQLite database in the executable Jar?
编辑
当我将DB文件放在源文件夹 Project / src / DatabaseFile
中并将路径更改为 jdbc:sqlite :src / DatabaseFile
,它在Eclipse上运行,但在运行Jar文件时再次运行 java -jar Project.jar
。它说:
When I placed the DB file in the source Folder Project/src/DatabaseFile
and changed the path to jdbc:sqlite:src/DatabaseFile
, it worked on Eclipse but again when running the Jar file as java -jar Project.jar
. It said:
path to 'src/DatabaseFile': 'C:\Users\name\src' does not exist
我想我需要指定数据库的相对路径。
I think I need to specify a relative path for the database.
编辑
这是我连接数据库的方式:
This is how I connect to the database:
public Connection getConnection(){
try{
Class.forName("org.sqlite.JDBC").newInstance();
con = DriverManager.getConnection("jdbc:sqlite:src/DatabaseFile");
} catch (Exception e) {
Log.fatal("Méthode: getConnection() | Class : SQLiteConnection | msg system : " + e.getMessage());
}
return con;
}
推荐答案
你用的是什么库? SQLite?
What library are you using for SQLite?
我根据您指定的连接URI进行了搜索,找到了这一个。在文档中,它说:
I did a search based on the connection URI you indicated and found this one. In the documentation it says:
2009年5月19日:sqlite-jdbc-3.6.14.1发布。此版本支持jdbc:sqlite :: resource:语法,以访问JAR归档中包含的只读DB文件,或通过URL,本地文件地址等指定的外部资源(另请参阅详细信息)
如果那是您正在使用的驱动程序,那么我建议使用以下连接URI:
If that is the driver you are using, then I would suggest the following connection URI:
"jdbc:sqlite::resource:DatabaseFile"
关键是因为你的数据库在一个罐子里文件,它不能作为 FileInputStream
的文件进行访问。相反,它必须通过JVM对它的支持来访问(即使用 Class.getResource()
或 Class.getResourceAsStream()
)。请注意,jar文件中包含的资源是只读的。您将无法保存对数据库的任何更改。
The key is that since your database is in a jar file, it can not be access as a file with FileInputStream
. Instead it must be accessed through the JVM's support for it (namely with Class.getResource()
or Class.getResourceAsStream()
). Do note that resources contained within jar files are read-only. You won't be able to save any changes to your database.
这篇关于如何在可执行的Jar中包含SQLite数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!