Diamonds
Diamonds

Reputation: 117

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.

Upvotes: 0

Views: 104

Answers (2)

Ergaro
Ergaro

Reputation: 61

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

Upvotes: 1

superflash
superflash

Reputation: 125

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}")')

Upvotes: 0

Related Questions