How to insert a unique ID into each SQLite row?

2020-02-09 00:07发布

I have the following SQLite code. How do I insert an auto generating unique ID into each row?

    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")');

5条回答
对你真心纯属浪费
2楼-- · 2020-02-09 00:49

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")');
查看更多
相关推荐>>
3楼-- · 2020-02-09 00:52

for the INSERT, better provide a "null" value for the corresponding autoincrement value's question mark placeholder.

 tx.executeSql('INSERT INTO ENTRIES (id, data) VALUES (?, ?)', [null, "First row"]);
查看更多
▲ chillily
4楼-- · 2020-02-09 00:53

autoincrement is your friend buddy.

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
查看更多
甜甜的少女心
5楼-- · 2020-02-09 00:54

This worked perfectly for me

c.execute('INSERT INTO WEBSITES (url) VALUES (?)', [url])
查看更多
贼婆χ
6楼-- · 2020-02-09 01:07

You could define id as an auto increment column:

create table entries (id integer primary key autoincrement, data)

As MichaelDorner notes, the SQLite documentation says 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.

create table entries (id integer primary key, data)

This behavior is implicit and could catch inexperienced SQLite developers off-guard.

查看更多
登录 后发表回答