Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

android

sqlite

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.

like image 702
Tyler Collier Avatar asked Jul 12 '11 05:07

Tyler Collier


2 Answers

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();
    }
}
like image 178
Pang Avatar answered Oct 18 '22 22:10

Pang


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.

like image 38
Mat Avatar answered Oct 18 '22 20:10

Mat