我正在学习如何在python中使用sqlite3。我有一个简单的表,包含两列: ID和name。
我尝试使用以下命令向该表添加新列(我正在使用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‘(带有引号)。如何添加仅具有名称Group的列?
谢谢。
发布于 2012-03-29 23:17:12
当表名或列名与SQL关键字(如GROUP)相同时,会产生错误。您需要用将表名引起来,而不是‘’。因此,您可以使用:
alter table studentinfo add column `Group` integer发布于 2012-03-29 23:19:38
GROUP是一个SQLite关键字。
解决方案:将列命名为其他名称。
发布于 2012-03-29 23:18:08
问题在于执行ALTER TABLE命令的方式。通过在您指定的列名两边加上单引号,该列名是该名称的一部分。去掉引号,它就会像你所期望的那样工作。
仅供参考:您可以使用点-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>https://stackoverflow.com/questions/9928232
复制相似问题