Python 和 MySQL:简单 INSERT 出错

Python and MySQL : Error with simple INSERT

import mysql.connector
conn = mysql.connector.connect(host="localhost",user="root",password="password", database="database_name")
cursor = conn.cursor()
a = "abcd"
cursor.execute("INSERT INTO table_jeux (lien_fiche) VALUES (?)", (a))

这是我在执行脚本时遇到的错误:

ProgrammingError: 1064 (42000): Syntax error near to '?)' at line 1

感谢帮助,我真的不明白为什么。

您可能想要的是将变量 a 插入到您的 SQL 代码中,但它不起作用 - 解析器得到一个“?”你希望它有 "abcd"

你可以试试这个:

cursor.execute("INSERT INTO table_jeux (lien_fiche) VALUES ({})".format(a))

或(有点python2方式):

cursor.execute("INSERT INTO table_jeux (lien_fiche) VALUES (%s)", (a,))

如此处所述: https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-execute.html

尝试使用 f 字符串,

它应该看起来像这样:

cursor.execute(f'INSERT INTO student (student_name, student_email, courseid) VALUES ("{student_name}","{student_email}",{course_id})') 

其中 student_name、student_email 和 course_id 都是变量。

你的情况:

cursor.execute(f'INSERT INTO table_jeux (lien_fiche) VALUES ("{a}")')