pythonsqllist

Not enough arguments for format string error when inserting list into database SQL Python


I'm trying to insert a list into separate columns of a database

print inserter 
params = ['%s' for item in inserter]
sql_query = 'INSERT INTO tablename (column1, column2, column3, column4, column5, column6, column7) VALUES (%s,%s,%s,%s,%s,%s,%s);' % ','.join(params)
cursor.execute(sql_query)
db.commit

But I keep getting the error:

not enough arguments for format string

Does anyone know what I am doing wrong?


Solution

  • Anyone know what I am doing wrong?

    You are using string interpolation in a query. This is bad, mainly for 2 reasons:

    You should use a parametrized query:

    sql_query = '''INSERT INTO tablename (column1, column2, column3, 
                                          column4, column5, column6, column7)
                   VALUES (%s,%s,%s,%s,%s,%s,%s);'''
    
    cursor.execute(sql_query, inserter) # assuming inserter is a tuple/list of values