How to insert a unique ID into each SQLite row?

后端 未结 5 1677
孤街浪徒
孤街浪徒 2020-12-14 06:54

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         


        
相关标签:
5条回答
  • 2020-12-14 07:24

    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.

    0 讨论(0)
  • 2020-12-14 07:25

    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")');
    
    0 讨论(0)
  • 2020-12-14 07:27

    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
    
    0 讨论(0)
  • 2020-12-14 07:27

    This worked perfectly for me

    c.execute('INSERT INTO WEBSITES (url) VALUES (?)', [url])
    
    0 讨论(0)
  • 2020-12-14 07:50

    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"]);
    
    0 讨论(0)
提交回复
热议问题