繁体   English   中英

sqlite3 python添加列并更新值

[英]sqlite3 python adding columns and updating values

我正在学习如何在python中使用sqlite3。 我有一个包含2列的简单表:ID和名称。

我尝试使用以下命令在此表中添加新列(我正在ipython中工作):

conn = sqlite3.connect('mydatabase.db')
c = conn.cursor()

c.execute("alter table studentinfo add column Group integer")

我收到以下错误:

OperationalError: near "Group": syntax error

然后,根据SO上的示例,我尝试了

c.execute("alter table studentinfo add column 'Group' integer")

这工作了。 但是,我现在有另一个问题。 显然,列名是“'Group'”,而不仅仅是“ Group”。

例如,当我尝试更新以下三个命令中的此列中的值时,一个有效,而两个无效。

conn = sqlite3.connect('mydatabase.db')
c = conn.cursor()

c.execute("update studentinfo set Group=1 where ID <= 4") #This did not work.

我收到以下错误:

OperationalError: near "Group": syntax error

然后,我尝试在列名两边加上引号:

c.execute("update studentinfo set 'Group'=1 where 'ID' <= 4")
#This did not work either. Gives no error, but does not do anything. Records remain   
#unchanged. 

然后,我尝试使用Group周围的引号,而不使用ID周围的引号。 这很好。

c.execute("update studentinfo set 'Group'=1 where ID <= 4") #This worked fine.

也就是说,它将列名视为“组”(带引号)。 如何添加仅具有名称Group的列?

谢谢。

当表名或列名与SQL关键字(例如GROUP)相同时,将生成错误。 您需要用“`”而不是“'”来引用表名。 因此,您可以使用:

alter table studentinfo add column `Group` integer

GROUP是一个SQLite关键字。

解决方案:将您的列命名为其他名称。

问题在于您如何执行ALTER TABLE命令。 通过在列名两边加上单引号,可以指定名称的一部分。 删除引号,它应该会按预期工作。

仅供参考:您可以使用dot-s命令(.s)在sqlite3中查询架构。 它将为您显示真实的列名。 这是一个简单的示例:

SQLite version 3.7.9 2011-11-01 00:52:41
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> create table a( mycol1 INT );
sqlite> alter table a add column mycol2 int;
sqlite> alter table a add column 'mycol3' int;
sqlite> .s
CREATE TABLE a( mycol1 INT , mycol2 int, 'mycol3' int);
sqlite>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM