如何使用默认值将列添加到数据库

How to add column to database with default

我有一个数据库,我正在尝试向其中添加一列。此列应包含 timestamp 类型的信息,我希望每一行在完成后都具有相同的时间戳(当前时间)。

我目前尝试过:

cursor.execute('''ALTER TABLE my_table ADD COLUMN time timestamp DEFAULT ?''', (datetime.datetime.utcnow(),))

这导致 sqlite3.OperationalError: near "?": syntax error

然后我尝试了:

cursor.execute(f'''ALTER TABLE my_table ADD COLUMN time timestamp DEFAULT {datetime.datetime.utcnow()}''')

这导致 sqlite3.OperationalError: near "-": syntax error

还有,做

cursor.execute(f'''ALTER TABLE my_table ADD COLUMN time timestamp DEFAULT CURRENT_TIMESTAMP''')

结果为 sqlite3.OperationalError: Cannot add a column with non-constant default

如何添加新列并在该列中设置值? (通过 DEFAULT,或其他一些机制。)

SQLite 不允许添加具有非常量值的新列。所以这个:

alter table my_table add column my_time timestamp default current_timestamp;

... 产生错误:

Cannot add a column with non-constant default

一个简单的选择是重新创建 table。假设您有一个名为 id 的列,它看起来像:

create table my_table_new(
    id int primary key, 
     my_time timestamp default current_timestamp
);

insert into my_table_new(id) select id from my_table;
drop table my_table;  -- back it up first !
alter table my_table_new rename to my_table;

您可以先添加新列,然后将 table 中的每个现有行更新为所需的值:

ALTER TABLE my_table ADD COLUMN time;
UPDATE my_table SET time = CURRENT_TIMESTAMP;