lundi 25 avril 2016

Add an autoincrementing ID column to an existing table with Sqlite

Using Sqlite, I want to add an auto-incrementing ID column to an existing table which had previously no ID:

import sqlite3
db = sqlite3.connect(':memory:')
c = db.cursor()

c.execute('create table events (int weight, text str)')
c.execute('insert into events values(?, ?)', (1371, 'Test1'))
c.execute('insert into events values(?, ?)', (223, 'Test2'))
c.execute('select * from events'); print c.fetchall()
# [(1371, u'Test1'), (223, u'Test2')]

# add an autoincrementing ID to existing table
c.execute('alter table events add id int not null auto_increment primary key')

How to do it properly? I have this error:

sqlite3.OperationalError: near "auto_increment": syntax error

Aucun commentaire:

Enregistrer un commentaire