sqlite3 python添加列和更新值

Cur*_*arn 3 python sqlite

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

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

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

c.execute("alter table studentinfo add column Group integer")
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

OperationalError: near "Group": syntax error
Run Code Online (Sandbox Code Playgroud)

然后,基于这里的例子我试过,

c.execute("alter table studentinfo add column 'Group' integer")
Run Code Online (Sandbox Code Playgroud)

这很有效.但是,我现在有另一个问题.显然,列名称是"'Group'"而不仅仅是"Group".

例如,当我尝试更新此列中的值时,在以下三个命令中,一个工作,两个不工作.

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

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

我收到以下错误:

OperationalError: near "Group": syntax error
Run Code Online (Sandbox Code Playgroud)

然后我尝试在列名称周围添加引号:

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. 
Run Code Online (Sandbox Code Playgroud)

然后,我试着用引号Group而不是周围ID.这很好.

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

也就是说,它将列名称视为"组"(带引号).如何添加名称为Group的列?

谢谢.

Pin*_*nch 6

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

alter table studentinfo add column `Group` integer
Run Code Online (Sandbox Code Playgroud)