Android SQLite Insert or Update

后端 未结 8 1927
太阳男子
太阳男子 2020-12-04 09:38

as can be seen in the documentation the syntax to make insert or update is : INSERT OR REPLACE INTO

() VALUES (), my
8条回答
  •  醉梦人生
    2020-12-04 10:08

    The operation name for that is "upsert" and how I solve it is identifying the columns of your table that make a row UNIQUE.

    Example: _id, name, job, hours_worked

    The columns which we'll use are name and job.

    private int getID(String name, String job){
        Cursor c = dbr.query(TABLE_NAME,new String[]{"_id"} "name =? AND job=?",new String[]{name,job},null,null,null,null);
        if (c.moveToFirst()) //if the row exist then return the id
            return c.getInt(c.getColumnIndex("_id"));
        return -1;
    }
    

    In your database manager class:

    public void upsert(String name, String job){
        ContentValues values = new ContentValues();
        values.put("NAME",name);
        values.put("JOB",job);
    
        int id = getID(name,job);
        if(id==-1)
            db.insert(TABLE_NAME, null, values);
        else
            db.update(TABLE_NAME, values, "_id=?", new String[]{Integer.toString(id)});
    }
    

提交回复
热议问题