I have a button, when user clicks it it passes some value and im adding this value with cv.put("name", name), how can i avoid adding duplicates?
-
check where not exist command on sql it might help. or you can simply inner join your own table and check if it does exist or not.koksalb– koksalb2017-04-01 11:26:44 +00:00Commented Apr 1, 2017 at 11:26
-
stackoverflow.com/a/26326817/3998402 solves your problemhumazed– humazed2017-04-01 11:27:38 +00:00Commented Apr 1, 2017 at 11:27
-
On SO, either accept an answer, or write your own answer.CL.– CL.2017-04-01 18:36:17 +00:00Commented Apr 1, 2017 at 18:36
3 Answers
1- Make sure you have some appropriate constraint in your table, such as PRIMARY KEY or UNIQUE.
2-When inserting, add a value to this constrained column via ContentValues. If inserting the new row would violate some constraint, the conflicting rows are first deleted and then the new row is inserted.
ContentValues Val = new ContentValues();
Val.put("IDD", id);
Val.put("Category", cat);
long rows=db.insertWithOnConflict(TABLE_CATEGER, null, Val,SQLiteDatabase.CONFLICT_REPLACE);
System.out.print(rows);
db.close();
Log.d(TAG,""+ rows);
Gordon Linoff answer shows you how to make some columns UNIQUE
Comments
it`s better to do it in your database structure in your
SQLiteOpenHelper
db.execSQL("CREATE TABLE "+MyDatabaseColums.USERINFOEntry.TABLE_NAME+" ("
+ MyDatabaseColums.USERINFOEntry.U_id+ " INTEGER , "
+ MyDatabaseColums.USERINFOEntry.mrname+ " TEXT, "
+ MyDatabaseColums.USERINFOEntry.meEmail+ " TEXT, "
"UNIQUE ( " +YOUR_id+") ON CONFLICT IGNORE"+");";
this will ignore any conflict in your Field
or use
db.execSQL("CREATE TABLE "+MyDatabaseColums.USERINFOEntry.TABLE_NAME+" ("
+ MyDatabaseColums.USERINFOEntry.U_id+ " INTEGER , "
+ MyDatabaseColums.USERINFOEntry.mrname+ " TEXT, "
+ MyDatabaseColums.USERINFOEntry.meEmail+ " TEXT, "
"UNIQUE ( " +YOUR_id+") ON CONFLICT REPLACE"+");";
to replace when conflict in Field
Comments
I you have a table t and you do not want duplicate values of name, then the best method is to have the database maintain the integrity of the data.
SQL offers unique indexes/constraints just for this purpose. For instance, you can create a unique index on the data:
create unique index unq_t_name on t(name);
Any attempt to create a duplicate name value in t (whether by insert or update) will generate an error.