首页 > 解决方案 > 如何通过 Python 向 MySql 连接器提供输入

问题描述

通过使用 mysql-connector-python 包

mycursor = mydb.cursor()
new_pin = int(input("Enter Pin Number:"))
Pins_Entry = "INSERT INTO ATM_DEMO_PINS(PIN) VALUES(%s)"  # Middle Program 1
mycursor.execute(Pins_Entry, new_pin)
mydb.commit()

显示错误:

mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%s)' at line 3

标签: pythonmysql

解决方案


这似乎是 SO 上的常年错误,但您需要在打开准备好的语句模式的情况下获取游标:

mycursor = mydb.cursor(prepared=True)     # change is HERE
new_pin = int(input("Enter Pin Number:"))
Pins_Entry = "INSERT INTO ATM_DEMO_PINS(PIN) VALUES(%s)"  # Middle Program 1
mycursor.execute(Pins_Entry, (new_pin,))
mydb.commit()

您看到的错误与 MySQL 将查询解析为查询%s的文字部分而不是占位符是一致的。


推荐阅读