Insert list into my database using Python
I want to insert a list in my database but I can't.
Here is an example of what I need:
variable_1 = "HELLO" variable_2 = "ADIOS" list = [variable_1,variable_2] INSERT INTO table VALUES ('%s') % list
Can something like this be done? Can I insert a list as a value? When I try it, an error says that is because of an error in MySQL syntax
The answer to your original question is: No, you can't insert a list like that.
However, with some tweaking, you could make that code work by 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, that style of variable insertion leaves your code vulnerable to SQL injection attacks.
Instead, we recommend using Python's DB API and building a customized query string with multiple question marks for the data to be inserted:
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 docs shows how to pass arguments using the question marks and it explains why they are necessary (essentially, it assures correct quoting of your variables).