在将数据插入数据库之前,检查重复的值 [英] android check duplicate values before inserting data into database

查看:121
本文介绍了在将数据插入数据库之前,检查重复的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

    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)))检查此行代码,它一次又一次添加相同的记录。如何控制一个姓氏只能添加一次?

I want to have a lastname only once in my database. Even though I check with "if(!(recorded_lastname.equals(new_recorded_lastname)))" this line code to, it adds same records again and again. How can I control a lastname to add only once?

//它适用于第一个记录,但是从第二个记录开始,它再次添​​加一些姓氏。

//It works for the first record very well, but starting from the second record, it adds some lastname again and again....

推荐答案

在我看来,你正在检查数据库中的每个记录,一旦找到一个不包含给定的lastname,你添加记录到数据库。您应该累积检查结果,如下所示:

It seems to me that you are checking every record in the database, and as soon as you find one that does not contain the given lastname you add the record to the database. You should accumulate the results of the checks, something like this:

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

Though it would sure be better if you use SQLite tools to handle this kind of stuff. Like setting the column to UNIQUE.

这篇关于在将数据插入数据库之前,检查重复的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆