问题描述
我正在尝试在插入语句中使用占位符.
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()
title 是一个字符串.
titel is a 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 ->语句中占位符的语法错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!