Why does a delete rawQuery need a moveToFirst in order to actually delete the rows?

前端 未结 5 1216
难免孤独
难免孤独 2020-12-29 23:40

I have been struggling for hours trying to debug why the following delete query actually didn\'t delete anything even if the exact same query on the exact same database work

相关标签:
5条回答
  • 2020-12-30 00:04

    The answer why is because rawQuery actually doesn't execute til u call some method on returned cursor. moveToFirst, isAfterLast ..

    0 讨论(0)
  • 2020-12-30 00:07

    I cannot answer the why, but another solution is to use .execSQL(String) as posted here

    0 讨论(0)
  • 2020-12-30 00:10

    In my case also, the same thing has happened for DELETE, It ran successfully after calling "cursor.moveToFirst()". Same is the case with INSERT and UPDATE queries also. I have also observed that calling any method on the cursor for the above mentioned queries I have got the results correctly. Without calling any method of the cursor the desired effect is taking place. So, I think the answer to your question is : Query gets executed only when we call some method on the cursor.

    0 讨论(0)
  • 2020-12-30 00:25

    A rawQuery returns a Cursor of a result set, which is just a reference to the query results. You should just be using a straight delete() call. Take a look at the documentation:

    http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html

    or an SQLiteStatement:

    http://developer.android.com/reference/android/database/sqlite/SQLiteStatement.html

    0 讨论(0)
  • 2020-12-30 00:28

    Following example shows how it return cursor by rawQuery if we do not need to write moveToFirst().

    public Cursor deleteContact(int id) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_CONTACTS, KEY_ID + " = ?",new String[]{String.valueOf(id)});
        Cursor c = db.rawQuery("DELETE FROM "+TABLE_CONTACTS+" WHERE "+KEY_ID+" = "+id,null);
        db.close();
    
        //if we not return Type Cursor then in above code:
        // db.rawQuery("DELETE FROM "+TABLE_NAME+" WHERE "+KEY_ID+" = "+id,null).moveToFirst();
        // in this way no return Type necessary.
        return c;
    }
    
    0 讨论(0)
提交回复
热议问题