0

whenever I try to run a normal query all works perfectly fine. the code executes and I can get the results but whenever I try to use a prepared statement in python I keep getting the following error:

1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '? WHERE name = ?' at line 1

The code I'm trying to run:

cursor = con.db.cursor(prepared=True)
try:
   cursor.execute("SELECT * FROM %s WHERE name = %s", ('operations', 'check', ))
except mysql.connector.Error as error:
   print(error)
except TypeError as e:
   print(e)

I've tried also to change the tuple object to string and removed one of the '%s' just for checking. but I still get an error for the '%s' synax.

another thing I've tried is to use a dict object so I've changed the '%s' to '%(table)s' and '%(name)s' and used a dict of

{'table': 'operations', 'name': 'check'}

example:

   cursor.execute("SELECT * FROM %(table)s WHERE name = %(name)s", {'table': 'operations', 'name': 'check'})

but again it didn't worked and I still got the exception

am I missing something?

Thanks in advance!

-------- Edit --------

Thanks to @khelwood, I've fixed the problem. as @khelwood mentioned in comments the problem was because I tried to use the '%s' as a parameter for table name. python prepared statements can't handle parameters for things such as table names so thats what throwed the exception

4
  • You can't insert a table name as a query parameter. You can pass the name you're looking for as a parameter, but it should be in a tuple: ("check",) Commented Dec 30, 2020 at 11:08
  • 1
    @JailtonSilva The , is correct when you're passing query parameters to cursor.execute. Commented Dec 30, 2020 at 11:13
  • @khelwood Thanks, I didn't know that Commented Dec 30, 2020 at 11:19
  • @khelwood You were right, the problem was because I tried to insert the table name as a parameter. Thanks! Commented Dec 30, 2020 at 11:35

1 Answer 1

1

You can't insert a table name as a query parameter. You can pass the name you're looking for as a parameter, but it should be in a tuple: ("check",)

So

cursor.execute("SELECT * FROM operations WHERE name = %s", ("check", ))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.