Logging SQL queries in android

后端 未结 9 2317
野趣味
野趣味 2020-12-04 17:45

I am using the query functions in order to build the SQL queries for my tables. Is there a way to see the actual query that is run? For instance log it somewher

9条回答
  •  广开言路
    2020-12-04 18:23

    If you are using a ContentProvider to access the DB, this is how I got it logging the queries. Not a perfect solution, but it works for development

    @Override
      public boolean onCreate() {
        dbHelper = new MySQLiteHelper(getContext());
        database=dbHelper.getWritableDatabase();
    
        if(!database.isReadOnly())
          database.execSQL("PRAGMA foreign_keys=ON;");
        return true;
      }            
    
      SQLiteDatabase.CursorFactory cursorFactory = new SQLiteDatabase.CursorFactory() {      
        @Override
        public Cursor newCursor(SQLiteDatabase db, SQLiteCursorDriver masterQuery, String editTable, SQLiteQuery query) {
          Log.d(TAG, "Query: "+query);
    
          return new SQLiteCursor(db, masterQuery, editTable, query);
        }
      };
    
      @Override
      public Cursor query(Uri uri, String[] projection, String selection,
          String[] selectionArgs, String sortOrder) {
        String table =getTableName(uri);
    
        if(Constants.LOG_QUERIES){
          database = SQLiteDatabase.openOrCreateDatabase(database.getPath(), cursorFactory);
        }
    
        Cursor cursor =database.query(table,  projection, selection, selectionArgs, null, null, sortOrder);
        cursor.moveToFirst();
    
        return cursor;
      }
    

    It'll throw a DatabaseNotClosed exception, but you'll be able to see the query

提交回复
热议问题