skip to Main Content

I want to run the following code, but Python gives me an error
code :

select = input("ENTER USER FOR PASS RECOVERY :  ")
cursor.execute("SELECT COUNT(*) FROM user_stat WHERE usr=(%s)",(select))

python code
error :

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 '%s)' at line 1

error picture
In which part of the code is the problem and what should I do?

3

Answers


  1. You have to use {} instead of ()
    select = input("ENTER USER FOR PASS RECOVERY : ")
    cursor.execute("SELECT COUNT(*) FROM user_stat WHERE usr={%s}",(select))

    Login or Signup to reply.
  2. The second argument to cursor.execute must be an iterable of params, So you should pass them as:

    1. A list: [select]
    2. A tuple: (select, ). Note that passing (select) does not make it a tuple.

    And another question, which client do you use to connect to MySQL? Some clients use ? as param placeholders and not %s

    Login or Signup to reply.
  3. if you need more examples or more help similar post is here -> How to use variables in SQL statement in Python?

    Also take a look at Kashyap (https://stackoverflow.com/a/21734918/2561174) comment with a good/bad query practices, he give this example on how to use it:

    # Do this instead
    t = ('RHAT',)
    cur.execute('SELECT * FROM stocks WHERE symbol=?', t)
    

    Wish it helps you!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search