android在将数据插入数据库之前检查重复值

时间:2012-05-18 19:16:19

标签: android database sqlite

    String new_recorded_lastname="a lastname";
    ////record to database......
    Cursor cursor = db.rawQuery("SELECT lastname FROM people; ",null);

     if (cursor != null){
  while(cursor.moveToNext()){

    String recorded_lastname=cursor.getString(cursor.getColumnIndex("lastname"));
    if(!(recorded_lastname.equals(new_recorded_lastname))){ 
    //add new_recorded_lastname to database
    break;
    }
    }
    }

我想在我的数据库中只使用一次姓氏。 即使我检查" if(!(recorded_lastname.equals(new_recorded_lastname)))"这行代码,它一次又一次地添加相同的记录。如何控制姓氏只能添加一次?

//它非常适用于第一条记录,但是从第二条记录开始,它会一次又一次地添加一些姓氏....

1 个答案:

答案 0 :(得分:3)

在我看来,您正在检查数据库中的每条记录,并且一旦找到不包含给定姓氏的记录,就会将记录添加到数据库中。您应该累积检查结果,如下所示:

boolean lastnamePresent = false;
while(cursor.moveToNext()){
    String recorded_lastname=cursor.getString(cursor.getColumnIndex("lastname"));
    if(recorded_lastname.equals(new_recorded_lastname)){ 
        lastnamePresent = true;
        break;
    }
}

if(!lastnamePresent)
    // add new_record_lastname to database

虽然使用SQLite工具来处理这类东西肯定会更好。就像将列设置为UNIQUE