MySQL/Python -> Wrong Syntax for Placeholder in Statements?

三世轮回 提交于 2019-12-02 11:05:10

问题


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.)

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.

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.


回答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,)



来源:https://stackoverflow.com/questions/49925982/mysql-python-wrong-syntax-for-placeholder-in-statements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!