You were trying to create a column with a name like 17-02-15
, but you were not successful because column names containing spaces or "funny characters" need to be quoted. The following example uses SQLite which accepts the ANSI standard double-quote ("column name"
), but other DBMSs may use other characters, e.g., MySQL tends to use backquotes (`column name`
) and Microsoft SQL Server usually uses square brackets ([column name]
).
Test code:
import datetime
import sqlite3
conn = sqlite3.connect(':memory:')
crsr = conn.cursor()
sql = 'CREATE TABLE TRACKER (id INT PRIMARY KEY)'
print(sql)
crsr.execute(sql)
conn.commit()
print("Test table created.")
print("")
val = str(datetime.datetime.now().strftime("%y-%m-%d"))
sql = 'ALTER TABLE TRACKER ADD %s INTEGER' % val
print(sql)
try:
crsr.execute(sql)
conn.commit()
print("Column added.")
except Exception as ex:
print(repr(ex))
print("")
# now try with quotes around the column name
sql = 'ALTER TABLE TRACKER ADD "%s" INTEGER' % val
print(sql)
try:
crsr.execute(sql)
conn.commit()
print("Column added.")
except Exception as ex:
print(repr(ex))
print("")
sql = 'SELECT * FROM TRACKER'
crsr.execute(sql)
print("Current column names:")
print([x[0] for x in crsr.description])
crsr.close()
conn.close()
Console output:
CREATE TABLE TRACKER (id INT PRIMARY KEY)
Test table created.
ALTER TABLE TRACKER ADD 17-02-15 INTEGER
OperationalError('near "17": syntax error',)
ALTER TABLE TRACKER ADD "17-02-15" INTEGER
Column added.
Current column names:
['id', '17-02-15']
Note also that different DBMSs may have other restrictions on column names, e.g., some may insist that a column name not begin with a numeric digit.