使用多列检查重复的Android sql

时间:2013-02-20 17:27:04

标签: android sqlite

我需要根据多列中的信息检查重复记录。如果我只使用一列来检查,我可以让它工作,但我需要它来检查三列,如果所有三列匹配,则显示吐司。下面的代码运行,但没有任何内容写入数据库。如果我从if语句中删除了两个字符串,它可以正常工作并写入db。我尝试过使用多个游标,但在尝试检查多个列的重复项时,我得到了相同的结果。

private void saveState() {

    Calendar calendar = Calendar.getInstance();
    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
    eventDate = sdf.format(calendar.getTime());

    String date = eventDate;
    String event = eventTitle.getText().toString();
    String empID = result;

    Cursor cursor = mDbHelper.fetchAllEntries();

    while (cursor.moveToNext()) {

    String enteredDate = cursor.getString(cursor.getColumnIndex("date"));
    String enteredEvent = cursor.getString(cursor.getColumnIndex("event"));
    String enteredEmpId = cursor.getString(cursor.getColumnIndex("empID"));

        if ( (enteredEmpId.equals(empID)) && (enteredDate.equals("date") && (enteredEvent.equals(event)))) {
            Toast.makeText(this, "Employee has already been scanned for this event.", Toast.LENGTH_LONG).show();  
        } else {
            mDbHelper.createEntry(date, event, empID);
        }
    }
}

如果需要,以下是来自我的Helper类的fetchAllEntries():

public Cursor fetchAllEntries() {

    return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_DATE,
            KEY_EVENT, KEY_EMPID}, null, null, null, null, null);
}

编辑: 我得到它来展示吐司,但由于某种原因它仍在写入数据库。我也注意到长时间呆在屏幕上的烤面包。我认为这是因为它在while循环中并且在完成之前不会消失。我之前忘了提到,这个应用程序正在扫描条形码,所以它需要能够识别扫描发生时是否已经扫描了日期和事件。这是更新的代码

private void saveState() {

    Calendar calendar = Calendar.getInstance();
    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
    eventDate = sdf.format(calendar.getTime());

    String date = eventDate;
    String event = eventTitle.getText().toString();
    String empID = result;

    Cursor cursor = mDbHelper.fetchAllEntries();

    if (cursor.getCount() == 0) {

        mDbHelper.createEntry(date, event, empID);

    } else if (cursor.getCount() > 0 ) {

    while (cursor.moveToNext()) {

    String enteredDate = cursor.getString(cursor.getColumnIndex("date"));
    String enteredEvent = cursor.getString(cursor.getColumnIndex("event"));
    String enteredEmpId = cursor.getString(cursor.getColumnIndex("empID"));

         if ((enteredDate.equals(date)) && (enteredEvent.equals(event)) && (enteredEmpId.equals(empID))) {

            Toast.makeText(this, "Employee has already been scanned for this event.", Toast.LENGTH_SHORT).show();  

        } else {

            mDbHelper.createEntry(date, event, empID);

        }
    }
}

}

1 个答案:

答案 0 :(得分:0)

检查多于1行是否具有相同的值:

SELECT COUNT(*) FROM myTable WHERE column1 = 'x' AND column2 = 'y' AND column3 = 'z'

如果count超过1,则有重复项,得到第一行的id:

SELECT id FROM myTable WHERE column1 = 'x' AND column2 = 'y' AND column3 = 'z' LIMIT 1

现在删除其余行:

DELETE * FROM myTable WHERE column1 = 'x' AND column2 = 'y' AND column3 = 'z' AND id != myId