SQL 如何在每个 SQLite 行中插入唯一 ID?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9342249/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to insert a unique ID into each SQLite row?
提问by sevens
I have the following SQLite code. How do I insert an auto generating unique ID into each row?
我有以下 SQLite 代码。如何在每一行中插入自动生成的唯一 ID?
tx.executeSql('DROP TABLE IF EXISTS ENTRIES');
tx.executeSql('CREATE TABLE IF NOT EXISTS ENTRIES (id unique, data)');
tx.executeSql('INSERT INTO ENTRIES (id, data) VALUES (1, "First row")');
tx.executeSql('INSERT INTO ENTRIES (id, data) VALUES (2, "Second row")');
回答by Andomar
You could define id
as an auto increment column:
您可以定义id
为自动增量列:
create table entries (id integer primary key autoincrement, data)
As MichaelDorner notes, the SQLite documentationsays that an integer primary key
does the same thing and is slightly faster. A column of that type is an alias for rowid
, which behaves like an autoincrement column.
正如 MichaelDorner 所指出的,SQLite 文档说 aninteger primary key
做同样的事情,而且速度稍快一些。该类型的列是 的别名rowid
,其行为类似于自动增量列。
create table entries (id integer primary key, data)
This behavior is implicit and could catch inexperienced SQLite developers off-guard.
这种行为是隐含的,可能会让没有经验的 SQLite 开发人员措手不及。
回答by Wim
This is the syntax that I use.
这是我使用的语法。
id INTEGER PRIMARY KEY AUTOINCREMENT,
Simply don't provide data for the autoincrement column
简单地不要为自动增量列提供数据
tx.executeSql('INSERT INTO ENTRIES (id, data) VALUES (NULL, "First row")');
Or even simpler
或者更简单
tx.executeSql('INSERT INTO ENTRIES (data) VALUES ("First row")');
回答by greut
autoincrement
is your friend buddy.
autoincrement
是你的朋友哥们。
CREATE TABLE IF NOT EXISTS ENTRIES (id integer primary key autoincrement, data);
INSERT INTO ENTRIES (data) VALUES ("First row");
INSERT INTO ENTRIES (data) VALUES ("Second row");
and then:
进而:
> SELECT * FROM?ENTRIES;
1|First row
2|Second row
回答by netalex
for the INSERT, better provide a "null" value for the corresponding autoincrement value's question mark placeholder.
对于 INSERT,最好为相应的自动增量值的问号占位符提供一个“空”值。
tx.executeSql('INSERT INTO ENTRIES (id, data) VALUES (?, ?)', [null, "First row"]);
回答by oriolowonancy
This worked perfectly for me
这对我来说非常有效
c.execute('INSERT INTO WEBSITES (url) VALUES (?)', [url])