问题描述
我正在尝试在插入语句中使用占位符.
I am trying to use placeholder in an insert-statement.
我正在使用PyCharm/Python 3.6,一个MySQL数据库和mysql.connector(不完全了解它们中的哪一个.)
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是一个字符串.
titel is a string.
这是插入的内容,但是我需要将titel-string插入该行.
This is what gets inserted, but I need to have the titel-string into that row.
删除值括号中的'时,PyCharm给我一个错误,提示MySQL语法不正确.
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.
推荐答案
您需要删除%s
中的引号,并确保您的参数位于元组中:
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()
当元组中有单个值时,必须包含尾随逗号:(item,)
When you have a single value in a tuple, you must include a trailing comma: (item,)
这篇关于MySQL/Python->语句中占位符的语法错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!