How to update sqlite table if records exist else insert?

后端 未结 3 425
孤独总比滥情好
孤独总比滥情好 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:37

    you must check if it is exist. Do it like this code:

     private Cursor selectOneItem(int id) {
        String strQuery = String.format(
                "SELECT * FROM %s WHERE %s = %s", Model_Task_List.KEY_table,
                Model_Task_List.KEY_id, id);
        Cursor cur = db.rawQuery(strQuery , null);
        return cur;
    }
    

    use above code to your insert function like below:

     public void insert(Model_Task_List modelobj) {
             Cursor cur = selectOneNews(modelobj.getTaskID());
            SQLiteDatabase db = this.getWritableDatabase();
            ContentValues values = new ContentValues();
            values.put(Model_Task_List.KEY_username, modelobj.getUserName());
            values.put(Model_Task_List.KEY_subject,modelobj.getSubject());
            values.put(Model_Task_List.KEY_task, modelobj.getTaskStatus());
            values.put(Model_Task_List.KEY_taskid,modelobj.getTaskID());
            values.put(Model_Task_List.KEY_owner,modelobj.getUserid());
            if (cur == null || cur.getCount() == 0) {
                        db.insert(Model_Task_List.KEY_table, null, values);
                    } else {
                        String[] args = {modelobj.getTaskID() + ""};
                        db.update(Model_Task_List.KEY_table, values,
                                Model_Task_List.KEY_id + "=?", args);
                    }
            db.close();
    
        }
    

提交回复
热议问题