Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/tfs/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 如何使用默认值向数据库添加列_Sql_Python 3.x_Sqlite_Date_Create Table - Fatal编程技术网

Sql 如何使用默认值向数据库添加列

Sql 如何使用默认值向数据库添加列,sql,python-3.x,sqlite,date,create-table,Sql,Python 3.x,Sqlite,Date,Create Table,我有一个数据库,我正试图向其中添加一列。此列应包含类型为timestamp的信息,并且我希望在完成时每一行都具有相同的时间戳(当前时间) 我目前已尝试: cursor.execute(''ALTER TABLE my_TABLE ADD COLUMN time timestamp DEFAULT?'',(datetime.datetime.utcnow(),)) 这将导致sqlite3.OperationalError:near”“:语法错误 于是我试着: cursor.execute(f''

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

我目前已尝试:

cursor.execute(''ALTER TABLE my_TABLE ADD COLUMN time timestamp DEFAULT?'',(datetime.datetime.utcnow(),))
这将导致
sqlite3.OperationalError:near”“:语法错误

于是我试着:

cursor.execute(f''ALTER TABLE my_TABLE ADD COLUMN time timestamp DEFAULT{datetime.datetime.utcnow()}')
这将导致
sqlite3.OperationalError:near“-”:语法错误

还有,做什么

cursor.execute(f''ALTER TABLE my_TABLE ADD COLUMN time timestamp DEFAULT CURRENT_timestamp')
导致
sqlite3.OperationalError:无法添加默认值为非常量的列


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

SQLite不允许添加具有非常量值的新列。因此:

alter table my_table add column my_time timestamp default current_timestamp;
。。。生成错误:

Cannot add a column with non-constant default
一个简单的选择是重新创建表。假设您有一个名为
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;

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

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

这回答了你的问题吗?我从中了解到“时间戳”显然是错误的,我应该使用
TEXT
值。。。当我将其更改为
文本
时,我的格式设置不再像以前那样有效-我必须对此进行研究。非常奇怪的是,一个未文档化的类型可以工作,但文档化的类型却不能。我发现了这一点——SQLite确实有一个。它用于转换为Python的
datetime.datetime