简体   繁体   English

python将数据插入sqlite3表

[英]python insert data into sqlite3 table

I am using python 3.7 and sqlite3 to write data to my database.我正在使用 python 3.7 和 sqlite3 将数据写入我的数据库。 I have this function我有这个功能

def add_item(self, item):
    stmt = "INSERT INTO users (id) VALUES (?)"
    args = (item,)
    self.conn.execute(stmt, args)
    self.conn.commit()

It works fine but it only allows me to write data to id column.它工作正常,但它只允许我将数据写入 id 列。 How can I make this function dynamic so that I can add any data to any column?我怎样才能使这个函数动态化,以便我可以向任何列添加任何数据?

# new variable to specify column to write to

def add_item(self, item, column):
    stmt = "INSERT INTO users (column) VALUES (?)"
    args = (item,)
    self.conn.execute(stmt, args)
    self.conn.commit()

You need to build the list of column names and value placeholders dynamically, based on the lengths of the lists of columns and values provided.您需要根据提供的列和值列表的长度动态构建列名称和值占位符列表。

This is can be done using str.join , however you may need to handle the case where a caller passes a single string as a column name, and a single value.这可以使用str.join完成,但是您可能需要处理调用者将单个字符串作为列名和单个值传递的情况。

def add_item(self, values, columns):
    # Check for single column insert
    if isinstance(columns, str):
        values, columns = (values,), (columns,)
    assert len(values) == len(columns), 'Mismatch between values and columns'

    template = """INSERT INTO users ({}) VALUES ({})"""

    cols = ','.join([f'"{col}"' for col in columns])
    placeholders = ','.join(['?'] * len(values))
    stmt = template.format(cols, placeholders)

    self.conn.execute(stmt, values)
    self.conn.commit()
    return

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM