从 SQLite 中的 INSERT OR IGNORE 语句查找自动增量值 [英] Finding Auto Incremented values from an INSERT OR IGNORE statement in SQLite
问题描述
我有一个名为图像"的表:
I have a table called "images":
CREATE TABLE images (
id INTEGER PRIMARY KEY AUTOINCREMENT,
url TEXT NOT NULL UNIQUE,
caption TEXT
);
在插入一行时,我希望 URL 列是唯一的.同时,我想找出具有该 URL 的行的 id.
On inserting a row, I'd like the URL column to be unique. At the same time, I'd like to find out the id of the row with that URL.
INSERT OR IGNORE images (url, caption) VALUES ("http://stackoverflow.com", "A logo");
SELECT last_insert_rowid(); -- returns the id iff there was an insert.
当然,我想尽快完成,尽管我的第一个想法是遵循以下伪代码的行:
Of course, I'd like to do it as quickly as possible, though my first thought was along the the lines of the following pseudo code:
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.insertWithOnConflict
.链接.
In Android 2.2 you can use SQLiteDatabse.insertWithOnConflict
. Link.
返回新的行ID插入的行 OR 的主键现有行如果输入参数'冲突算法' = CONFLICT_IGNOREOR -1 如果有任何错误OR -1 如果有任何错误
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 中,您可以:
In older versions of SDK you can:
- 查询条目是否存在
- 如果找到条目 - 返回所选项目的 id
- 如果没有找到 - 使用
SQLiteDatabse.insert
插入条目(它将返回新项目的主键).
- query if entry exists
- If entry found - return id of selected item
- If nothing found - insert entry using
SQLiteDatabse.insert
(it will return primary key of new item).
如果需要,还可以考虑使用事务.
Also consider using transactions if needed.
这篇关于从 SQLite 中的 INSERT OR IGNORE 语句查找自动增量值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!