MySQL/Python ->语句中占位符的语法错误?

MySQL/Python -gt; Wrong Syntax for Placeholder in Statements?(MySQL/Python -语句中占位符的语法错误?)
本文介绍了MySQL/Python ->语句中占位符的语法错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在插入语句中使用占位符.

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 ->语句中占位符的语法错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)