Adding varible in SQL command not working with Select statment HELP please

Question:

x = int(id_[0])
select_query = "SELECT * FROM files WHERE id = %s"
cursor.execute(select_query,x)
results = cursor.fetchone()

I am using mySQL in python
This is the error i get:
mysql.connector.errors.ProgrammingError: 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 ‘%s’ at line

It workds when i get rid of the varible and just add a random id like 1.

Asked By: Tamer Vassib

||

Answers:

You forgot to add string delimiters around your %s, so SQL is trying to process that as a variable name or column name. Furthermore, for regex expressions like the one you have, try using LIKE instead of =

To fix the SQL syntax errors, your query should look something like this:

x = int(id_[0])
select_query = "SELECT * FROM files WHERE id LIKE '%s'"
cursor.execute(select_query,x)
results = cursor.fetchone()
Answered By: Dominic
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.