【问题标题】:room pragma query房间语用查询
【发布时间】:2018-06-18 16:56:17
【问题描述】:

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

为什么这个语句不起作用?

database.openHelper.readableDatabase.query("PRAGMA wal_checkpoint")

【问题讨论】:

    标签: android sqlite android-sqlite android-room


    【解决方案1】:

    我遇到了这个问题,发现解决方案是检查查询结果。 我刚刚检查了第一列 int,如果参数为 FULL、RESTART 或 TRUNCATE 并且调用被阻止 (see this.),它将为 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");
    

    【讨论】:

      【解决方案2】:

      如何使用 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 
      

      为什么这个语句不起作用?

      我不确定,但我认为这取决于 Room 控制力很强。

      【讨论】:

        猜你喜欢
        • 2020-07-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多