Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sqlite3 python adding columns and updating values

Tags:

python

sqlite

I am learning how to use sqlite3 in python. I have a simple table with 2 columns: ID and name.

I tried adding a new column to this table using the following commands (I am working in ipython):

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

c.execute("alter table studentinfo add column Group integer")

I get the following error:

OperationalError: near "Group": syntax error

Then, based on the examples here on S.O. I tried,

c.execute("alter table studentinfo add column 'Group' integer")

This worked. However, I have another problem now. Apparently the column name is "'Group'" instead of just "Group".

For example, when I try to update the value in this column, of the following three commands, one works and two do not.

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

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

I get the following error:

OperationalError: near "Group": syntax error

Then I tried to put quotes around column names:

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. 

Then, I tried with quotes around Group but not around ID. This worked fine.

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

That is, it thinks of the column name as 'Group' (with the quotes). How do I add a column with just the name Group?

Thank you.

like image 298
Curious2learn Avatar asked May 09 '26 08:05

Curious2learn


2 Answers

When table name or column name is the same as SQL keywords (such as GROUP), errors are generated. You need to quote the table name with ` `, not ' '. So you could use:

alter table studentinfo add column `Group` integer
like image 133
Pinch Avatar answered May 11 '26 22:05

Pinch


GROUP is an SQLite keyword.

Resolution: Name your column something else.

like image 29
brice Avatar answered May 11 '26 22:05

brice