以下 Python 代码出现错误:
import mysql.connector
cnx = mysql.connector.connect(user='root', password='',
host='127.0.0.1',
database='DB')
cursor = cnx.cursor()
Name = "James"
Department = "Finance"
StartYear = 2001
CurrentPos = 2001
Link = ""
add_user = ("INSERT INTO DB.tbluser "
"(username, department, startyear, currentpos, link) "
"VALUES (%s, %s, %d, %d, %s)")
data_user = (Name, Department, StartYear, CurrentPos, Link)
cursor.execute(add_user, data_user)
cnx.commit()
cursor.close()
cnx.close()
错误信息是
mysql.connector.errors.ProgrammingError: Not all parameters were used in the SQL statement
你明白为什么吗?
最佳答案
参数标记是 %s
而不是 %d
。
add_user = """INSERT INTO DB.tbluser
(username, department, startyear, currentpos, link)
VALUES (%s, %s, %s, %s, %s)"""
请注意 parameter markers mysql.connector
使用的可能看起来与 Python 字符串格式化中使用的 %s
相同,但这种关系只是巧合。一些数据库适配器,如 oursql
和 sqlite3
使用 ?
作为参数标记而不是 %s
。
关于python - 并非所有参数都在 SQL 语句中使用(Python、MySQL),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20818155/