1

I am trying to use placeholder in an insert-statement.

I am using PyCharm/Python 3.6, a MySQL-Database, and the mysql.connector (don't know which of them exactly.)

enter image description here

Why doesn't the following code work?

insert_stmt = "INSERT INTO mydb.datensatz (Titel) VALUES ('%s');"
data = (titel)
cursor.execute(insert_stmt, data)
cnx.commit() 

titel is a string.

This is what gets inserted, but I need to have the titel-string into that row. enter image description here

When deleting the ' ' in the values-braces, PyCharm gives me an error with incorrect MySQL-syntax.

How to use placeholders in this case? How could I use more placeholders for example at inserting into more columns than one? Research didn't help.

4
  • I haven't done much more than play around with python a bit when it was new; but would parenthesis around the query string itself as shown in the official example here make a difference? Commented Apr 19, 2018 at 16:33
  • @Uueerdo Sadly it makes no difference, as it still inserts %s into that specific row. Commented Apr 19, 2018 at 16:37
  • According to the example you should not be be putting ''s around the %s... I just looked up PyCharm, is it just an IDE "intellisense-style error", or does it actually refuse to run the query? Commented Apr 19, 2018 at 16:49
  • @Uueerdo Without those quotes, it gives me an SQL-Syntax-Error, so they are needed I suppose :/ Commented Apr 19, 2018 at 17:01

1 Answer 1

1

You need to remove the quotes from the %s AND make sure your parameters are a in a tuple:

insert_stmt = "INSERT INTO mydb.datensatz (Titel) VALUES (%s);" # Removed quotes around %s
data = (titel,) # Added trailing comma to make tuple
cursor.execute(insert_stmt, data)
cnx.commit()

When you have a single value in a tuple, you must include a trailing comma: (item,)

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.