2012-02-18 12 views
20

Ho il seguente codice SQLite. Come posso inserire un ID univoco di generazione automatica in ogni riga?Come inserire un ID univoco in ogni riga SQLite?

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

risposta

27

Si potrebbe definire id come auto increment column:

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

Come osserva MichaelDorner, il SQLite documentation dice che un integer primary key fa la stessa cosa ed è leggermente più veloce . Una colonna di quel tipo è un alias per rowid, che è behaves like an autoincrement column.

Questo comportamento è implicito e potrebbe catturare offici sviluppatori SQLite inesperti.

+1

avviso, che "La parola chiave AUTOINCREMENT impone extra CPU, memoria, spazio su disco, e il disco sovraccarico I/O e dovrebbe essere evitato se non strettamente necessario. E ' di solito non è necessario. " (https://www.sqlite.org/autoinc.html) –

+0

@MichaelDorner: Grazie, interessante, ho aggiornato la risposta. – Andomar

+2

Nota che * deve * essere 'intero' e non 'int' in PHP con PDO, altrimenti non imposta automaticamente l'id. – starbeamrainbowlabs

2

autoincrement è tuo amico amico.

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

e poi:

> SELECT * FROM ENTRIES; 
1|First row 
2|Second row 
14

Questa è la sintassi che utilizzo.

id INTEGER PRIMARY KEY AUTOINCREMENT, 

Semplicemente non forniscono i dati per la colonna autoincrement

tx.executeSql('INSERT INTO ENTRIES (id, data) VALUES (NULL, "First row")'); 

O ancora più semplice

tx.executeSql('INSERT INTO ENTRIES (data) VALUES ("First row")'); 
0

per l'inserto, meglio fornire un valore "null" per il valore autoincrement corrispondenti di punto interrogativo segnaposto.

tx.executeSql('INSERT INTO ENTRIES (id, data) VALUES (?, ?)', [null, "First row"]); 
0

questo ha funzionato perfettamente per me

c.execute('INSERT INTO WEBSITES (url) VALUES (?)', [url])