2012-03-29 124 views
3

我正在学习如何在python中使用sqlite3。我有一个简单的2列表:ID和名称。sqlite3 python添加列和更新值

我试着用下面的命令增加一个新的列到这个表(我在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的列?

谢谢。

回答

6

当表名或列名与SQL关键字(如GROUP)相同时,会生成错误。你需要用``而不是''来引用表名。所以你可以使用:

alter table studentinfo add column `Group` integer 
+0

Duv and also @brice:不记得GROUP是关键字。将更改列名称。谢谢。 – Curious2learn 2012-03-29 15:24:45

1

麻烦的是你如何执行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> 
3

GROUP是一个SQLite关键字。

解决方案:为您的列命名。