Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/307.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
sqlite3 python添加列和更新值_Python_Sqlite - Fatal编程技术网

sqlite3 python添加列和更新值

sqlite3 python添加列和更新值,python,sqlite,Python,Sqlite,我正在学习如何在python中使用sqlite3。我有一个简单的表,有两列:ID和name 我尝试使用以下命令向该表添加一个新列(我正在使用ipython): 我得到以下错误: OperationalError: near "Group": syntax error OperationalError: near "Group": syntax error 然后,根据我在S.O.上的例子 c.execute("alter table studentinfo add column 'Group'

我正在学习如何在python中使用sqlite3。我有一个简单的表,有两列:ID和name

我尝试使用以下命令向该表添加一个新列(我正在使用ipython):

我得到以下错误:

OperationalError: near "Group": syntax error
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.
然后我尝试在列名周围加引号:

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. 
也就是说,它将列名视为“组”(带引号)。如何添加仅包含名称组的列


谢谢。

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

alter table studentinfo add column `Group` integer

问题在于如何执行ALTERTABLE命令。通过在作为名称一部分的指定列名周围包含单引号。去掉引号,它就会像你期望的那样工作

仅供参考:您可以使用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>

GROUP
是一个SQLite关键字


解决方案:将您的专栏命名为其他内容。

Duv和@brice:不记得GROUP是一个关键字。将更改列名。谢谢
alter table studentinfo add column `Group` integer
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>