如何检查Android数据库中的重复名称? [英] How to check duplicates name in android database?
问题描述
我想从两个编辑文本中输入姓名和电话号码.我使用两个按钮保存并使用列表视图在模拟器中显示它.输入名称后,当我单击保存按钮时,如何检查我是否已经输入相同的名称.我是android的新手,将非常有帮助.
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;
}
推荐答案
我将首先通过添加NOT NULL和UNIQUE约束来更改表定义.
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
将返回新记录的ID,或在错误时返回-1(并且如果没有唯一名称,则约束失败将是错误).
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
将返回新记录的ID或现有行的主键(如果输入参数'conflictAlgorithm'= CONFLICT_IGNORE或-1,如果有任何错误).
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.
就我个人而言,我将使用设置了CONFLICT_IGNORE标志的insertWithOnConflict
.这样,您可以获取重复记录的行ID(以及不让重复记录被输入).
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).
这篇关于如何检查Android数据库中的重复名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!