更新Android现有行中的字段

时间:2018-04-17 19:58:34

标签: java android sql sqlite android-contentprovider

你好我在接收到存储在DB上的项目时的情况如下我必须执行插入,如果匹配唯一字段的行不存在,则更新行中的特定字段。我试过这个,我面临着一个例外

android.database.sqlite.SQLiteConstraintException: column title is not unique (code 19)

如何安全地实现上述情况

1 个答案:

答案 0 :(得分:0)

您可以使用UPDATE OR IGNORE

但是,如果您使用的是SQLiteDatabase update方法,则无法指定此方法。

您要么使用updateWithOnConflict方法。 SQLiteDatabase - updateWithOnConflict

  • 使用冲突算法CONFLICT_IGNORE
  • 该方法返回更新的行数。

或者你可以预先检查

的唯一性
Cursor csr = dbhlpr.query(
    your_table,
    new String[]{your_column},
    your_column + "=?",
    new String[]{your_value_as_a_string},
    null,
    null,
    null
);
if (csr.getCount() < 1) {
    //.. do the update here using the `update` method
} else {
    //.. handle not able to insert as unique  here
}
csr.close();
相关问题