How to check duplicates name in android database?

2020-04-23 07:39发布

问题:

I want to enter name and phone number from two edit text.i use two buttons to save and show it in emulator using list view.After entering name and when i click save button how to check whether i have already entered the same name. i am new to android explanation will be really helpful.

public void onCreate(SQLiteDatabase db) {

    db.execSQL("CREATE TABLE "+tbname+"("+Key_id+" INTEGER PRIMARY KEY AUTOINCREMENT, "+Key_name+" TEXT,"+Key_mobile+" TEXT)");

}

public void n(String aa, String bb) {
    SQLiteDatabase db=this.getWritableDatabase();
    ContentValues cv=new ContentValues();
    cv.put(Key_name, aa);
    cv.put(Key_mobile, bb);
    db.insert(tbname, Key_name, cv);

    db.close();

}

public Cursor cr()

{
    SQLiteDatabase db=getReadableDatabase();
    String [] colms=new String[]{Key_id+" as _id",Key_name,Key_mobile};
    Cursor cur=db.query(tbname, colms, null, null, null, null, null);
    cur.moveToFirst();
    return cur;



}

回答1:

I would start with changing your table definition by adding the NOT NULL and UNIQUE constraints.

db.execSQL("CREATE TABLE "+tbname+"("+Key_id+" INTEGER PRIMARY KEY AUTOINCREMENT, "+Key_name+" TEXT NOT NULL UNIQUE,"+Key_mobile+" TEXT)"); 

Then you have a choice of methods to use for your insert. You can use:

insertOrThrow will return the id of your new record, or -1 on an error (and a constraint failure of not having a unique name would be an error).

insertWithOnConflict will return the id of the new record OR the primary key of the existing row if the input param 'conflictAlgorithm' = CONFLICT_IGNORE OR -1 if any error.

Personally, I would use insertWithOnConflict with the CONFLICT_IGNORE flag set. That way you can get the row id back for the duplicate record (as well as not letting the duplicate get entered).



回答2:

Put UNIQUE in your table field definition an then use insertOrThrow. If you insert the same, insertOrThrow will cause an exception, you can intercept it.