How to prevent duplicate value from being inserted into sqlite database (if duplicate and then overwrite)

I created two tables in my database. In both tables, I insert the value at the same time, now what I want to do is that I want to insert the record into the second table, but the condition is that if these are two identical records, then I want to insert only one record, not a duplicate value. In the second table there are two fields: id , and the second category , when the user inserts two identical categories this time I want to insert only one record, below is my code that does not work properly, Inserts all records that take a 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;
         }
        }
+4
5

ContentValues, writableDatabase

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

EDIT:

, , ,

    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 . , , . , : -/ .

+6

( ). , .

+2

, , .

,

INSERT OR REPLACE INTO TABLE_CATEGER(value1,value2,value3)
0
source

Use the following query

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

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

0
source

This works for me, and I also created the 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
source

All Articles