【问题标题】:Updating field in a existing row Android更新现有行中的字段 Android
【发布时间】:2018-04-17 19:58:34
【问题描述】:

您好,在收到要存储在 DB 上的项目时,我处于以下情况,如果不存在与唯一字段匹配的行,则必须执行插入,否则更新该行中的特定字段。我试过了,我正面临

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

如何安全无一例外地实现上述场景

【问题讨论】:

  • 是主列中的标题列吗?
  • 不,我还有另一个主列 Title is just Unique @Jarvis

标签: java android sql sqlite android-contentprovider


【解决方案1】:

你可以使用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();

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多