How to check duplicates name in android database?

偶尔善良 提交于 2019-12-02 03:56:44

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!