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.
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
GROUP is an SQLite keyword.
Resolution: Name your column something else.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With