How to update sqlite table if records exist else insert?

后端 未结 3 424
孤独总比滥情好
孤独总比滥情好 2021-01-17 01:06

This may be duplicate question but am confused as am new for sql and android am getting response from server need to save it in sqlite db if values in the table already exis

3条回答
  •  野的像风
    2021-01-17 01:43

    The update() function returns how many rows were affected. So if there were none, you know that you must insert instead:

    void updateIfExistsElseInsert(...) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = ...;
        values.put( /* all except the ID */ );
        int rows = db.update(KEY_TABLE, values, KEY_ID + " = " + id, null);
        if (rows == 0) {
            values.put(KEY_ID, id);
            db.insert(KEY_TABLE, null, values);
        }
    }
    

提交回复
热议问题