【发布时间】:2018-01-06 04:43:42
【问题描述】:
我正在使用 sqlite3 包通过类实现来创建、连接和管理 sqlite 数据库。在一种方法中,我创建了一个数据库,在下一种方法中,我尝试使用? 的参数替换在该数据库中创建一个表。但是,sqlite 不会接受该命令。我哪里出错了,如何让 python-sqlite 接受 execute 命令来创建表头?下面附上我的示例代码。
class ManageDatabase:
def __init__(self, database, table_name):
self.database = database
self.table_name = table_name
def create_database(self):
# This function works so I will omit the details
def connect_to_database(self):
# This function also works
self.conn = sqlite3.connect(self.database)
self.cur = self.conn.cursor()
def create_table(self, headers):
# headers = ['id integer primary key', 'Column1 REAL', 'Column2 TEXT']
# - In this case, headers has 3 entries, but this can be whatever
# the user wants and the code must be able to adapt
''' This is where the code runs into trouble '''
query = 'CREATE TABLE {tn} (?);'.format(tn=self.table_name)
self.cur.execute(query, (*headers, ))
self.conn.commit()
if __name__ == "__main__":
data = ManageDatabase('Test.db', 'db_table')
# - The database already exists, but does not have a table,
# so there is no need to use data.create_database()
data.connect_to_database() # This command executes successfully
headers = ['id integer primary key', 'Column1 REAL', 'Column2 TEXT']
data.create_table(headers)
此时我收到错误sqlite3.OperationalError: near "?": syntax error。如何编写此代码以使其与 headers 列表中的数据一起使用,并且还可以足够灵活以允许用户输入 5、6 或他们选择的许多标题列和数据类型?
【问题讨论】:
-
问题是
(?)是一个值(sql 转义)。您正在尝试插入 3 个项目,因此您需要(?,?,?)。表名和列名不适合 sql 转义值概念,因为它被单引号和内部单引号加倍等。您的第一个标题将变为'id integer primary key',这将是不正确的。虽然我没有用表名或列名测试过。
标签: database python-3.x sqlite