Add an autoincrementing ID column to an existing table with Sqlite

An SQLite table cannot modified in a significant manner using alter table once it has been created. One common popular suggestion is to create a new table with the existing fields as well as the additionally required field and copy/import your data into the new one and optionally delete the old one.

c.execute('create table events_copy(id integer primary key autoincrement, weight integer,str text)')
c.execute('insert into events_copy(weight, str) select weight, str from events')
c.execute('drop table events')
c.execute('alter table events_copy rename to events')
c.commit()

Tags:

Python

Sql

Sqlite