Search code examples
androidsqlitesqliteopenhelper

How can I update a single (or multiple, but not all) columns in an SQLiteDatabase?


I use a SQLitDatabase for my project, which I normally update by:

  • Getting all the values one row contains (let's say v1, v2 and v3)
  • Putting all the values back, and replacing the ones I need to be updated.

Example:

I want to update v2.

ContentValues values = new ContentValues();
    values.put(v1_COLUMN, v1);        // Old value, gotten earlier
    values.put(v2_COLUMN, v2_new);    // New value, calculated earlier
    values.put(v3_COLUMN, v3);        // Old value, gotten earlier
db.update(TABLE_name, values, "_id=?", new String[]{id});  

I use this method, even if I only have to update 1 column (keep in mind some of my tables have more then 3 columns).

How can I update only the column that actually needs updating?


Solution

  • your code is OK but don't need to put old value to values. just put new value

    ContentValues values = new ContentValues();
    values.put(v2_COLUMN, v2_new);    // New value, calculated
    db.update(TABLE_name, values, "_id=?", new String[]{id});