我正在学习如何在 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
然后,基于 S.O.我试过了,
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
关于python - sqlite3 python 添加列和更新值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9928232/