Python Sqlite3将列添加到以数字

时间:2020-09-26 02:49:34

标签: python database sqlite identifier quoting

我正在尝试使用ALTER TABLE命令将列添加到现有表中。由于列名的前导数字,我没有找到解决无法识别的令牌错误的解决方案。

列名示例:column = 1abc

到目前为止,我还没有尝试过以下方法。

sql = '''ALTER TABLE {table} ADD COLUMN {column} {data_type};'''.format(table=table, column=column, data_type=data_type)
self.cursor.execute(sql)

sql = '''ALTER TABLE ? ADD COLUMN ? ?;'''
self.cursor.execute(sql, (table, column, data_type))

sql = '''ALTER TABLE %s ADD COLUMN %s %s;''' % (table, column, data_type)
self.cursor.execute(sql)

我了解我需要对查询进行参数化,但是我不确定如何使它与ALTER TABLE命令一起使用。

我得到的错误输出:

unrecognized token: "1abc"

1 个答案:

答案 0 :(得分:1)

列名必须为quoted,并用双引号 *

>>> conn = sqlite3.connect(':memory:')
>>> DDL1 = """CREATE TABLE test ("col1" TEXT);"""
>>> cur.execute(DDL1)
<sqlite3.Cursor object at 0x7f98a67ead50>
>>> conn.commit()
>>> DDL2 = """ALTER TABLE test ADD COLUMN "{}" TEXT"""
>>> cur.execute(DDL2.format('1abc'))
<sqlite3.Cursor object at 0x7f98a67ead50>
>>> conn.commit()
>>> cur.execute("""SELECT * FROM test;""")
<sqlite3.Cursor object at 0x7f98a67ead50>
>>> cur.description
(('col1', None, None, None, None, None, None), ('1abc', None, None, None, None, None, None))

* 反引号(``)和方括号[]也可用于引用,但文档将其描述为非标准方法。