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

Cli*_*ote 5 java database jdbc

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

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

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

Ale*_*lex 5

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

加载后,程序将检查数据库是否存在,如果不在数据库中,则只需播放安装SQL脚本即可创建数据库结构和初始数据,否则,您可以继续进行,只需执行应用程序执行的操作即可创建要做。

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

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

create table foobar(bazz VARCHAR);
insert into foobar values('foo');
insert into foobar values('bar');
// and so on
Run Code Online (Sandbox Code Playgroud)

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

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();
}
Run Code Online (Sandbox Code Playgroud)

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

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


小智 1

我会研究h2。这是一个很棒的数据库,有许多持久选项。另外,由于您使用的是 Java,我会考虑研究 hibernate。