Python Insert Data Into Sqlite3 Table
I am using python 3.7 and sqlite3 to write data to my database. I have this function def add_item(self, item): stmt = 'INSERT INTO users (id) VALUES (?)' args = (item,)
Solution 1:
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.
defadd_item(self, values, columns):
# Check for single column insertifisinstance(columns, str):
values, columns = (values,), (columns,)
assertlen(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
Post a Comment for "Python Insert Data Into Sqlite3 Table"