Home > front end >  how to correctly pass a list into a MySQL query in python 3
how to correctly pass a list into a MySQL query in python 3

Time:05-20

I'm trying to pass a list of data into a MySQL database but for the life of me I can't figure out what I'm doing wrong, even after scouring the internet for a solution I decided to post a question here.

I can connect to the database no problem, and sending simple queries like 'SHOW TABLES' work like a charm, but when trying to pass the contents of a list into MySQL just doesn't work. this code here is as close as i got to it working, but I get an error because of an email address.

the error is: "You have an error in your SQL syntax... near '@gmail.com, x123, False ..."

cursorObject = database.cursor()

#data is a list of lists
data = [['w0', 'firstName', lastName', [email protected]', 'x123', False, '12345', [], Europe, True], ...]     

for i in data:
   queryString = 'INSERT IGNORE INTO `database` (foo1, foo2, foo3, foo4, foo5, foo6,
   foo7, foo8, foo9, foo10) VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)'  % (i[0], i[1], 
   i[2], i[3], i[4], i[5], i[6], i[7], i[8], i[9])

   cursorObject.execute(queryString)

do you have any idea why the '@' in the email is causing an error? and also, I don't know if I am accidently making myself vulnerable to sql injections. I tried formatting the code with something like

stringData = ', '.join(['%'] * len(i))

and then adding i as the second parameter in the query, but then I just get an 'Python type list cannot be converted' error. I get the same error when I wrap i in a tuple.

ps. I changed the real data in data to placeholder text, but it should work the same.

CodePudding user response:

For your first question, you forgot to add quotes to your strings. You should put '%s' (with quotes around the %s) so that the final query would contain properly quoted strings.

For your second question, (a) using join instead of format does NOT protect you from SQL injection, and (b) you didn't include the actual data...

But the real answer, would be to AVOID completely to build a string with embedded parameter values, and use prepared statements instead. You don't say which python module you use for connecting, please check the documentation. In case of the MySql Connector/Python, you may use statement.execute(queryString, (tuple with the data to insert)) as shown here: https://dev.mysql.com/doc/connector-python/en/connector-python-example-cursor-select.html

  • Related