使用jooq将内存sqlite db备份到字节数组

时间:2018-11-01 13:41:36

标签: java sql sqlite jooq

private byte[] inMemSqliteDbBackup() {
    byte[] data = null;
    try (DSLContext dsl = DSL.using("jdbc:sqlite::memory:") {
        ...
        //insert some data 
        dsl.execute("backup to " + data); // backup to byte[], but unsupported , a file is needed 
        dsl.connection(connection -> {
            // or, get underlying connection and open inputstream 
            // but there is no getInputStream in SqliteConnection
        });
    }
    return data;
}

我们如何在内存sqlite db中备份到byte []? 我经历了SqliteConnection,它也没有提供InputStream。

一个选择是不使用url作为“ jdbc:sqlite:/some-location”在内存db中使用,然后我们可以使用FileUtils.readFileToByteArray(new File(some-location)),但是不确定是否可以在内存sqlite db中使用相同的功能使用Jooq的DSLContext。

1 个答案:

答案 0 :(得分:1)

backup to语法不是本机SQLite SQL语法,而是offered by the Xerial JDBC driver according to their docs here

  

将整个数据库备份到backup.db文件:

     
// Create a memory database
Connection conn = DriverManager.getConnection("jdbc:sqlite:");
Statement stmt = conn.createStatement();
// Do some updates
stmt.executeUpdate("create table sample(id, name)");
stmt.executeUpdate("insert into sample values(1, \"leo\")");
stmt.executeUpdate("insert into sample values(2, \"yui\")");
// Dump the database contents to a file
stmt.executeUpdate("backup to backup.db");
Restore the database from a backup file:
// Create a memory database
Connection conn = DriverManager.getConnection("jdbc:sqlite:");
// Restore the database from a backup file
Statement stat = conn.createStatement();
stat.executeUpdate("restore from backup.db");

如果对它们的源进行反向工程,则可以看到该命令已被拦截,并在org.sqlite.core.NativeDB中转换为该特定方法:

native synchronized int backup(byte[] dbNameUtf8, byte[] destFileNameUtf8,
        ProgressObserver observer) throws SQLException;

即它绑定到SQLite备份API,该API仅可用于实际文件,而不能用于内存中的数据结构。

因此,恐怕对于当前版本的SQLite,无论使用jOOQ还是JDBC或本机,都无法在不编写中间临时文件的情况下拦截该备份并将其发送到byte[]变量中直接使用SQLite