Tamer Vassib
Tamer Vassib

Reputation: 25

Adding variable in SQL command not working with Select statement

Code:

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 works when I get rid of the variable and just add a random id like 1.

Upvotes: 0

Views: 40

Answers (1)

Dominic
Dominic

Reputation: 513

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()

Upvotes: 0

Related Questions