使用Java .jar文件提供数据库?

我想创建一个程序,用户只需运行.jar文件即可运行。 我希望这个程序能够访问数据库,该数据库在首次下载程序时预先填充了一些数据,并且当用户使用它时,会向数据库添加更多数据。

数据库应本地存储在用户的计算机上。

我最好的选择是什么? 我应该使用哪个数据库引擎,以及我需要做些什么才能使用户在安装应用程序时不必设置数据库,它将预先填充.jar文件?

一个简单的解决方案是使用本地存储在磁盘上的嵌入式数据库(例如在jar文件附近)。 您可以使用h2 ,甚至是sqlite 。

加载程序时会检查数据库是否存在,如果不在这里,只需播放一个设置SQL脚本,创建数据库结构和初始数据,否则你很好,只需要做你的应用程序的东西。创造了做。

这是一个非常简单的h2数据库示例:

假设您在JAR的/resources/文件夹中打包一个名为init.sql的SQL文件,它将创建一个表,如:

 create table foobar(bazz VARCHAR); insert into foobar values('foo'); insert into foobar values('bar'); // and so on 

然后在代码中的某个位置,您需要访问数据,您将尝试加载数据库或创建数据库(如果它尚不存在)。

 Connection loadDatabase() throws Exception { Class.forName("org.h2.Driver"); Connection con = null; try { // throws an exception if the database does not exists con = DriverManager.getConnection("jdbc:h2:./foo.db;ifexists=true"); } catch (SQLException e) { // if the database does not exists it will be created conn = DriverManager.getConnection("jdbc:h2:./foo.db"); // init the db initDatabase(con); } return con; } void initDatabase(Connection con) throws Exception { // load the init.sql script from JAR InputStreamReader isr = new InputStreamReader( getClass().getResourceAsStream("/resources/init.sql")); // run it on the database to create the whole structure, tables and so on RunScript.execute(con, isr); isr.close(); } void doSomeStuffWithDb() throws Exception { Connection con = loadDatabase(); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("select * from foobar"); // will print foo, then bar while (rs.next()) { System.out.println(rs.getString(1)); } rs.close(); stmt.close(); conn.close(); } 

执行之后,您的应用程序旁边应该有一个名为foo.db的文件,其中包含创建的表等。

这是一个非常简单的例子,当然你可以使用JDBC周围的任何包装来避免使用ResultSet等,比如spring jdbcTemplate,甚至可以加载连接实例等。

使用Java DB ,然后当用户第一次启动程序时,将脚本加载到它。

我会调查h2 。 这是一个很棒的数据库,有许多持久的选项。 此外,既然你正在使用Java,我会考虑研究hibernate。