【问题标题】:Finding Auto Incremented values from an INSERT OR IGNORE statement in SQLite从 SQLite 中的 INSERT OR IGNORE 语句中查找自动增量值
【发布时间】:2010-09-25 16:39:08
【问题描述】:

我有一个名为“images”的表格:

CREATE TABLE images (
    id      INTEGER PRIMARY KEY AUTOINCREMENT, 
    url     TEXT NOT NULL UNIQUE,
    caption TEXT
);

在插入一行时,我希望 URL 列是唯一的。同时,我想找出那个 URL 所在行的 id。

INSERT OR IGNORE images (url, caption) VALUES ("http://stackoverflow.com", "A logo");
SELECT last_insert_rowid(); -- returns the id iff there was an insert.

当然,我想尽快完成,虽然我的第一个想法是按照以下伪代码的行:

int oldID = execSQL("SELECT last_insert_rowid()");
execSQL("INSERT OR IGNORE images (url, caption) VALUES ('http://stackoverflow.com', 'A logo')");
int newID = execSQL("SELECT last_insert_rowid()");
if (newID != oldID) {
     // there was an insert. 
     return newID;
} else {
     // we'd already seen this URL before
     return execSQL("SELECT id FROM images WHERE url = 'http://stackoverflow.com'");
}

但这似乎毫无希望地低效。

从 INSERT OR IGNORE 语句中获取自动递增行 ID 的最高效方法是什么。

【问题讨论】:

    标签: sql android sqlite


    【解决方案1】:

    在 Android 2.2 中,您可以使用 SQLiteDatabse.insertWithOnConflictLink.

    返回新的行ID 插入的行或主键 如果输入参数,则存在行 'conflictAlgorithm' = CONFLICT_IGNORE 或 -1(如果有任何错误)或 -1(如果有任何错误)

    在旧版本的 SDK 中,您可以:

    1. 查询条目是否存在
    2. 如果找到条目 - 返回所选项目的 ID
    3. 如果没有找到 - 使用 SQLiteDatabse.insert 插入条目(它将返回新项目的主键)。

    如果需要,还可以考虑使用事务。

    【讨论】:

    • 我发现这个 API 调用没有按预期工作。耻辱。我也支持回到 1.5。
    猜你喜欢
    • 2019-04-19
    • 2011-10-19
    • 1970-01-01
    • 1970-01-01
    • 2011-12-09
    • 2013-04-12
    • 1970-01-01
    • 2015-04-30
    • 2011-10-20
    相关资源
    最近更新 更多