Skip to content
Advertisement

Python Sqlite3 insert operation with a list of column names

Normally, if i want to insert values into a table, i will do something like this (assuming that i know which columns that the values i want to insert belong to):

conn = sqlite3.connect('mydatabase.db')
conn.execute("INSERT INTO MYTABLE (ID,COLUMN1,COLUMN2)
VALUES(?,?,?)",[myid,value1,value2])

But now i have a list of columns (the length of list may vary) and a list of values for each columns in the list.

For example, if i have a table with 10 columns (Namely, column1, column2…,column10 etc). I have a list of columns that i want to update.Let’s say [column3,column4]. And i have a list of values for those columns. [value for column3,value for column4].

How do i insert the values in the list to the individual columns that each belong?

Advertisement

Answer

As far as I know the parameter list in conn.execute works only for values, so we have to use string formatting like this:

import sqlite3
conn = sqlite3.connect(':memory:')
conn.execute('CREATE TABLE t (a integer, b integer, c integer)')
col_names = ['a', 'b', 'c']
values = [0, 1, 2]
conn.execute('INSERT INTO t (%s, %s, %s) values(?,?,?)'%tuple(col_names), values)

Please notice this is a very bad attempt since strings passed to the database shall always be checked for injection attack. However you could pass the list of column names to some injection function before insertion.

EDITED:
For variables with various length you could try something like

exec_text = 'INSERT INTO t (' + ','.join(col_names) +') values(' + ','.join(['?'] * len(values)) + ')'
conn.exec(exec_text, values)
# as long as len(col_names) == len(values)
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement