Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

android

sqlite

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 condition is that, if there is two same record then I want insert only one record not duplicate value, In second table there is two field one is id and second is category, when user insert two same category that time I want to insert only one entry, below is my code which is not working properly, It insert all record accept duplicate value..

public long InsertCat(String idd, String cat) 
  { 
     try 
       {
        SQLiteDatabase db;
        long rows = 0;
        db = this.getWritableDatabase(); 
        ContentValues Val = new ContentValues();
        Val.put("IDD", idd); 
        Val.put("Category", cat);
        Cursor c = db.rawQuery("SELECT * FROM " + TABLE_CATEGER + " WHERE Category='"+cat+"'",null);
        while(c.moveToNext())
        {
            if(c.getString(0).equals(cat))
            {
                flag=true;
            }
        }           
        if(flag==true)
        {
          rows=db.update(TABLE_CATEGER, Val, "Category='"+cat+"'"  , null);     
          System.out.print(rows);
          db.close();
        }
        if(flag==false)
        {
            rows = db.insert(TABLE_CATEGER, null, Val);
            System.out.print(rows);             
            db.close();
        }
        return rows; // return rows inserted.
         } catch (Exception e) {
         return -1;
         }
        }
like image 565
Ravi Avatar asked Oct 12 '14 15:10

Ravi


Video Answer


2 Answers

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..

like image 110
Panther Avatar answered Sep 20 '22 23:09

Panther


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.

like image 26
Tarun Tak Avatar answered Sep 20 '22 23:09

Tarun Tak