Get updated rows count from SQLite in Android using a raw query?

前端 未结 4 800
不思量自难忘°
不思量自难忘° 2020-12-07 01:14

How can I get the number of rows updated using an update statement in SQLite in Android?

Note that I need to use some type of raw execute of a SQL state

相关标签:
4条回答
  • 2020-12-07 01:50

    You could do your insert whichever way you want, and then do a select and use the changes() function to return the number of affected rows.

    0 讨论(0)
  • 2020-12-07 01:55

    To expand on Mat's answer, here's the example code for getting the updated row count:

    Cursor cursor = null;
    try
    {
        cursor = db.rawQuery("SELECT changes() AS affected_row_count", null);
        if(cursor != null && cursor.getCount() > 0 && cursor.moveToFirst())
        {
            final long affectedRowCount = cursor.getLong(cursor.getColumnIndex("affected_row_count"));
            Log.d("LOG", "affectedRowCount = " + affectedRowCount);
        }
        else
        {
            // Some error occurred?
        }
    }
    catch(SQLException e)
    {
        // Handle exception here.
    }
    finally
    {
        if(cursor != null)
        {
            cursor.close();
        }
    }
    
    0 讨论(0)
  • 2020-12-07 02:01

    You can use SQLiteStatement.executeUpdateDelete method for this:

    SQLiteDatabase db = getReadableDatabase();
    SQLiteStatement statement = db.compileStatement("[your sql here]");
    int affectedRows = statement.executeUpdateDelete();
    

    The same method used internally in SQLiteDatabase.update(...) methods.

    0 讨论(0)
  • 2020-12-07 02:11

    Expanding on Mat and Pang's answers...

    Could we skip the Cursor and use simpleQueryForLong()?

    e.g.

    public long getChangesCount() {
        SQLiteDatabase db = getReadableDatabase();
        SQLiteStatement statement = db.compileStatement("SELECT changes()");
        return statement.simpleQueryForLong();
    }
    
    0 讨论(0)
提交回复
热议问题