Search code examples
pythonmysqlmysql-connector

How to use select statements with variables in mysql in python


I want to use a select statement with a variable within the where clause. Ive done resarch on this looking at How to use variables in SQL statement in Python? and Inserting Variables MySQL Using Python, Not Working. Ive tried to implement the solutions provided but its not working. Error code

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 '?' at line 1

Heres the code:

name = input("Write your name")
mycursor.execute("SELECT name FROM workers WHERE symbol=?", name)

What am i doing wrong?


Solution

  • Okay Spike7 this is exactly what is ideal,

    mycursor.execute("SELECT name FROM workers WHERE symbol=%s", (name,))  
    

    or

    mycursor.execute("SELECT name FROM workers WHERE symbol=?", (name,)) 
    

    The accepted answer at the first link you given explain evertything.