How to prevent to insert duplicate value in sqlite database (if duplicate then overwrite)

前端 未结 6 1284
余生分开走
余生分开走 2021-01-05 15:34

I had created two table in my database, In both table I am inserting value at the same time, now what I want to do is that, I want to insert record in second table, but the

6条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-05 16:23

    Put all your values inside ContentValues and then call this on writableDatabase

    db.insertWithOnConflict(tableName, null, contentValues,SQLiteDatabase.CONFLICT_REPLACE);
    

    EDIT:

    Well all you need is only this part of code

        SQLiteDatabase db;
        long rows = 0;
        db = this.getWritableDatabase(); 
        ContentValues Val = new ContentValues();
        Val.put("IDD", idd); 
        Val.put("Category", cat);
        rows = db.insertWithOnConflict(tableName, null, contentValues,SQLiteDatabase.CONFLICT_REPLACE);
    

    insertWithOnConflict methods follows the last parameter as the reaction algorithm when an duplicate row is Found. And for a duplicate row to be found, the primary keys has to clash. If all this satisfys the row would surely get Replaced :-/ If not something else is going wrong..

提交回复
热议问题