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

前端 未结 6 1157
余生分开走
余生分开走 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:21

    use insertWithOnConflict() method instead of insert()

    response = sqLiteDatabase.insertWithOnConflict(TABLE_TRACKER_LOGS_LINES, null, contentValues,SQLiteDatabase.CONFLICT_REPLACE);
    
    0 讨论(0)
  • 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..

    0 讨论(0)
  • 2021-01-05 16:26

    While creating your table, put constraint on your column(Primary key or Unique key).This will not only the duplicate value to be inserted into your database.

    0 讨论(0)
  • 2021-01-05 16:31

    Check with the primary key of which you want assign then while inserting check with on duplicate key.. if you want you update the row

    on duplicate key update

    As mentioned i am writing the code on duplicate key

    INSERT OR REPLACE INTO TABLE_CATEGER(value1,value2,value3)
    
    0 讨论(0)
  • 2021-01-05 16:34

    This is working for me,and i also created Category as a primary key..

    ContentValues Val = new ContentValues();
    Val.put("IDD", idd); 
    Val.put("Category", cat);
    long rows=db.insertWithOnConflict(TABLE_CATEGER, null,  Val,SQLiteDatabase.CONFLICT_REPLACE);
    System.out.print(rows);
    Log.d("kkkkkkkkkk",""+ rows);
    db.close();
    return rows; // return rows inserted.
    
    0 讨论(0)
  • 2021-01-05 16:36

    Use the following query

    INSERT OR REPLACE INTO table_name (idColoumn, categoryColumn) VALUES (?, ?)
    

    It will add new row if it does not exist or update row if it exists. hope this will help you.

    0 讨论(0)
提交回复
热议问题