10

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 statement, rather than do anything with ContentValues because I need a dynamic query. Thus I can't make use of the SQLiteDatabase.update() method. For example, I'm running something like

UPDATE my_table 
   SET field_name = field_name + 1

The methods I know of return void, e.g. SQLiteDatabase.execSQL(). SQLiteDatabase.rawQuery() returns a Cursor, but the cursor has zero rows and its count is always -1.

4 Answers 4

17

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Is that method available in the Android APIs?
It's a sqlite function. You use it in select queries - independent of the language you're using.
Ah. Great! I'd imagine it's wise to wrap such calls with transactions. So you'd do 1) begin tran 2) do update 3) get changes 4) end transaction. It works, thanks!
@Tyler Collier Could you provide an example how to select affected rows after update? Thanks!
@Gosha, click the changes() link in Mat's answer for help on changes().
12

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();
    }
}

1 Comment

I would use this simpler approach: cursor.getLong(0).
5

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();
}

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.