使用Python3创建sqlite表

时间:2018-01-06 04:43:42

标签: database python-3.x sqlite

我正在使用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或多个标题列和数据类型?< / p>

1 个答案:

答案 0 :(得分:1)

一种可能的解决方案是在format的帮助下将数据与join连接起来:

def create_table(self, headers):
    try:
        query = 'CREATE TABLE {tn} ({fields})'.format(tn=self.table_name, fields=",".join(headers))
        self.cur.execute(query)
        self.conn.commit()
    except sqlite3.Error as er:
        print(er)