How to check duplicates name in android database?

后端 未结 2 354
一整个雨季
一整个雨季 2021-01-25 08:20

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

相关标签:
2条回答
  • 2021-01-25 08:28

    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.

    0 讨论(0)
  • 2021-01-25 08:29

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

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