The answer to your original question: No, you cannot insert such a list.
However, with some tweaking, you can make this code using %r and passing in a tuple:
variable_1 = "HELLO" variable_2 = "ADIOS" varlist = [variable_1, variable_2] print "INSERT INTO table VALUES %r;" % (tuple(varlist),)
Unfortunately, this style of variable insertion leaves your code vulnerable to SQL injection attacks .
Instead, we recommend using the Python DB API and creating a custom query string with several question marks for the inserted data:
variable_1 = "HELLO" variable_2 = "ADIOS" varlist = [variable_1,variable_2] var_string = ', '.join('?' * len(varlist)) query_string = 'INSERT INTO table VALUES (%s);' % var_string cursor.execute(query_string, varlist)
The example at the beginning of the SQLite3 documentation shows how to pass arguments using question marks, and explains why they are necessary (in fact, it ensures that your variables are correctly quoted).
source share