0

I'm new to MySQLdb and Python. I'm trying to execute the following statement:

header_string = 'number_one, number_two, number_three'
values = '1, 2, 3'
cursor.execute("""INSERT INTO my_table (%s) VALUES (%s)""", (header_string, values))

and it returns with the following error:

Error: 1064 "You have an error in your SQL syntax."

From my limited understanding of MySQLdb the above execute statement should execute the following SQL statement:

INSERT INTO my_table (number_one, number_two, number_three) VALUES (1, 2, 3)

Any ideas what I might be doing wrong?

1
  • SQL doesn't allow variables to represent comma delimited values at runtime -- if you create the SQL query as a string & use the variables in Python before submitting the query, it should work. Commented Mar 1, 2011 at 18:15

1 Answer 1

6

Try:

header_string = ('number_one','number_two','number_three')
values = (1,2,3)
cursor.execute("""INSERT INTO my_table (%s,%s,%s) VALUES (%s,%s,%s)""", (header_string+values))
Sign up to request clarification or add additional context in comments.

3 Comments

That is still not going to work. MySQLdb escapes strings so that no SQL injection can occur in your code. That query will be translated into INSERT INTO my_table("number_one", "number_two", "number_three") VALUES (1, 2, 3), which is also syntactically wrong.
Actually it'll be translated into: INSERT INTO my_table(`number_one`, ...). Apparently it did work, since the answer was accepted.
My bad. I really thought mysqldb changed any string into its quoted form, and was unaware that it correctly handled column names. One learns new stuff every day :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.