简体   繁体   中英

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))

And this is the error I get when I execute the script :

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

Thanks for help, I really don't understand why.

What You probably want is to insert variable a into Your SQL code, but it doesn't work - and the parser gets a "?" where You want it to have "abcd"

You could try this:

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

or (in somewhat python2 manner):

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

as described here: https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-execute.html

Try using f strings,

It should look something like this:

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

where student_name, student_email and course_id are all variables.

In your case:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM