石榴的东西

问题描述 投票:0回答:2

如何使用Room数据库执行sql PRAGMA语句?

为什么这句话不起作用?

database.openHelper.readableDatabase.query("PRAGMA wal_checkpoint")
android sqlite android-sqlite android-room
2个回答
0
投票

如何使用Room数据库执行sql PRAGMA语句?

您可以覆盖@Database类的init方法,并在配置之前执行编译指示(或您希望绕过Room控制的其他数据库操作)。

EG : -

@Override
public void init(@NonNull DatabaseConfiguration configuration) {
    doPreRoomOpenStuff(configuration);
    super.init(configuration);
}

private void doPreRoomOpenStuff(DatabaseConfiguration dbconfig) {
    String dbpath = (dbconfig.context).getDatabasePath(DBNAME).getPath();
    if (ifDBExists(dbpath)) {
        SQLiteDatabase db = SQLiteDatabase.openDatabase(dbpath, null,Context.MODE_PRIVATE);
        Cursor csr = db.rawQuery("PRAGMA wal_checkpoint",null);
        while (csr.moveToNext()) {
            StringBuilder sb = new StringBuilder();
            for (int c = 0; c < csr.getColumnCount(); c++) {
                sb.append("\n\tColumnName = ").append(csr.getColumnName(c)).append(" Value=").append(csr.getString(c));
            }
            Log.d("INFO",sb.toString());
        }
        db.close();
    }
}

private boolean ifDBExists(String dbpath) {
    File db = new File(dbpath);
    if(db.exists()) return true;
    File dir = new File(db.getParent());
    if (!dir.exists()) {
        dir.mkdirs();
    }
    return false;
}

示例结果: -

06-18 18:22:14.244 1875-1875/? D/INFO:  ColumnName = busy Value=0
        ColumnName = log Value=-1
        ColumnName = checkpointed Value=-1 

为什么这句话不起作用?

我不确定,但我认为这是由房间控制得很好。


0
投票

我有这个问题,发现解决方案是检查查询的结果。我刚检查了第一列int,如果参数为FULL,RESTART或TRUNCATE,则该参数将为1,并且调用被阻止(see this.)。

Cursor c = room.query(new SimpleSQLiteQuery("pragma wal_checkpoint(full)"));
if(c.moveToFirst() && c.getInt(0) == 1)
    throw new RuntimeException("Checkpoint was blocked from completing");
© www.soinside.com 2019 - 2024. All rights reserved.