如果插入不存在? [英] Insert if not exists?

查看:137
本文介绍了如果插入不存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我提示用户将项目添加到SQLiteDb。当他们点击添加,我要检查,如果该项目已经存在...如果没有的话我想将其插入。

I'm prompting a user to add an item to an SQLiteDb. When they click add, I want to check if that item already exists... if it doesn't then I want to insert it.

我拨打电话

mDbHelper.createNote(inputLine.getText().toString().trim(), mTable[i]);

其中要求...

Which calls...

public long createNote(String value, String table) {
        ContentValues initialValues = new ContentValues();
        initialValues.put(table, value);

        return mDb.insert(table, null, initialValues);
    }

这就是作品,但它不检查,如果该项目已经存在,所以它仍然插入重复。所以,我想

Thats works but it doesn't check if the item already exists, so it still inserts duplicates. So I tried

return mDb.insertWithOnConflict(table, null, initialValues, SQLiteDatabase.CONFLICT_FAIL);

然而,它不显示识别insertWIthOnConflict或SQLiteDatabase.CONFLICT_FAIL ...

However, it doesn't appear to recognize insertWIthOnConflict or SQLiteDatabase.CONFLICT_FAIL...

我怎样才能得到这个工作?

How can I get this to work?

编辑:这是1台,2行。表名=注,行= _id,请注意。

it's 1 table, 2 rows. table name = note, rows = _id, note.

推荐答案

在这种情况下,我亲热这样的检查:

In such situation I perfrom such checking:

if (!checkRecordExist(DATABASE_TABLE, new String[] {KEY_1, KEY_2}, new String[] {value_1, value_2})) 
database.insert(DATABASE_TABLE, null, updateValues);

其中,

private boolean checkRecordExist(String tableName, String[] keys, String [] values) {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < keys.length; i++) {
        sb.append(keys[i])
            .append("=\"")
            .append(values[i])
            .append("\" ");
        if (i<keys.length-1) sb.append("AND ");
    }

    Cursor cursor = database.query(tableName, null, sb.toString(), null, null, null, null);
    boolean exists = (cursor.getCount() > 0);
    cursor.close();
    return exists;
}

这篇关于如果插入不存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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