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.exe
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.
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")');
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
This worked perfectly for me
c.execute('INSERT INTO WEBSITES (url) VALUES (?)', [url])
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"]);