sql - 从 SQLite 中的 INSERT OR IGNORE 语句中查找自动递增的值

标签 sql android sqlite

我有一个名为“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 的最高效方法是什么。

最佳答案

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

Returns the row ID of the newly inserted row OR the primary key of the existing row if the input param 'conflictAlgorithm' = CONFLICT_IGNORE OR -1 if any errorOR -1 if any error

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

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

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

关于sql - 从 SQLite 中的 INSERT OR IGNORE 语句中查找自动递增的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3794579/

相关文章:

php - Codeigniter 类似通配符

android-MNC 项目不会在 API 级别 'android-MNC' 之前的设备上运行

java - 如何删除android系统栏(页脚栏)

android - BiometricPrompt : Why should we check KeyguardManager. isDeviceSecure() 在启用 setDeviceCredentialAllowed 之前?

c# - 在嵌入式 Linux 上编程的最佳语言

java - 处理丢失的连接插入

python - SQLAlchemy 查询返回 None

phpmyadmin返回查询结果但php返回0

MySQL移动平均线计算使用CASE

java.sql.SQLException : [SQLITE_CONSTRAINT]