1

I'm trying to use this code to update a table on mySQL, but I'm getting error with the update part

table_name = 'my_table'
sql_select_Query = """ 
INSERT {0}  (age, city, gender,UniqueId)
VALUES ({1},{2},{3},{4})
ON DUPLICATE KEY UPDATE 
  age=VALUES(age,city=VALUES(city),gender=VALUES(gender),height=VALUES(height)
""".format(table_name,  '877','2','1','2898989')

    cursor = mySQLconnection .cursor()
    cursor.execute(sql_select_Query)
    mySQLconnection.commit()

For example, to update the city I get:

Unknow columns '877'

Hence it seems it is taking the value as a column name and search for then in my_table.

7
  • As a start I would print out the final sql query after the substitutions have been made. Commented Aug 7, 2019 at 23:12
  • You also seem to be missing a closing parenthesis after age, it should be age=values(age) Commented Aug 7, 2019 at 23:17
  • age=VALUES(age must be age=VALUES(age) but your string doesn't look like the parameterized mysql i come to know Commented Aug 7, 2019 at 23:18
  • @nbk this is not a parametrized query, this is string interpolation. Commented Aug 7, 2019 at 23:19
  • You are also missing height from the field list, while you have it in the update section. Commented Aug 7, 2019 at 23:21

1 Answer 1

1

The correct way to use parameters with Python is to pass the values in the execute() call, not to interpolate the values into the SQL query.

Except for identifiers like the table name in your case.

sql_select_Query = """
INSERT `{0}`  (age, city, gender, UniqueId)
VALUES (%s, %s, %s, %s)
ON DUPLICATE KEY UPDATE
  age=VALUES(age), city=VALUES(city), gender=VALUES(gender)
""".format(table_name)

cursor.execute(sql_select_Query, ('877', '2', '1', '2898989'))

See also MySQL parameterized queries

You forgot the ) after VALUES(age. Maybe that was just a typo you made transcribing the question into Stack Overflow. I've fixed it in the example above.

Your INSERT statement sets the height column, but it's not part of the tuple you insert. I removed it in the example above. If you want height in the UPDATE clause, then you need to include it in the tuple and pass a value in the parameters.

Also I put back-quotes around the table name, just in case the table name is a reserved keyword or contains a space or something.

Sign up to request clarification or add additional context in comments.

Comments

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.