如何使用 Room 数据库执行 sql PRAGMA 语句?
为什么这个说法不起作用?
database.openHelper.readableDatabase.query("PRAGMA wal_checkpoint")
如何使用 Room 数据库执行 sql PRAGMA 语句?
为什么这个说法不起作用?
database.openHelper.readableDatabase.query("PRAGMA wal_checkpoint")
我遇到了这个问题,发现解决方案是检查查询结果。我刚刚检查了第一列 int,如果参数为 FULL、RESTART 或 TRUNCATE 并且调用被阻止,它将为 1(请参阅此。)。
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");
如何使用 Room 数据库执行 sql PRAGMA 语句?
您可以覆盖 @Database 类的init方法,并在配置之前执行 pragma(或您想要绕过 Room 控制的其他数据库操作)。
例如:-
@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
为什么这个说法不起作用?
我不确定,但我认为这取决于房间的控制力。