1

I want to fetch all rows from MySQL table with

query = "SELECT * FROM %s WHERE last_name=%s"
cursor.execute(query, ("employees","Smith"))

but I'm getting You have an error in your SQL syntax. When I try

query = "SELECT * FROM employees WHERE last_name=%s"
cursor.execute(query, ("Smith",))

all is fine. Documentation says cursor.execute(operation, params=None, multi=False) The parameters found in the tuple or dictionary params are bound to the variables in the operation.link on docs

flebas
  • 99
  • 8

5 Answers5

1

The first will generate an SQL like this:

SELECT * FROM 'employees' WHERE last_name='smith'

The parameters are SQL quoted.

If you really need to have a table name as param, you must proceed in 2 steps:

table_name = 'employees'
query_tpl = "SELECT * FROM {} WHERE last_name=%s"
query = query_tpl.format(table_name)
cursor.execute(query, ("Smith",))
glenfant
  • 1,298
  • 8
  • 9
-1

you need to add the quote symbol. So the query will be like

SELECT * FROM employees WHERE last_name='Smith'

Change both your query to

query = "SELECT * FROM %s WHERE last_name='%s'"
query = "SELECT * FROM employees WHERE last_name='%s'"
Arijit Panda
  • 1,581
  • 2
  • 17
  • 36
-1

You can't use a parameter for the table name in the execute call. But you can use Python string interpolation for that:

query = "SELECT * FROM %s WHERE last_name=%s" %("employees","Smith")
cursor.execute(query)
Harsha Biyani
  • 7,049
  • 9
  • 37
  • 61
-1

You can't use a table name as a parameter. you are generating invalid sql with your code that is putting quotes around each string. the table name cannot have quotes around it.

sql you are generating

select * from 'employees' where last_name = 'Smith'

What sql you want

select * from employees where last_name = 'Smith'

you would have to format the string first like the example below.

query = "SELECT * from {} wherre last_name ='{}'"
cursor.execute(query.format("employees","Smith"))

using code like this does open up the possibility of SQL injection. so please bear that in mind.

ttallierchio
  • 460
  • 7
  • 17
-1
query="SELECT * FROM %s WHERE name=%s",(employees,smith)
cursor.execute(query)
rows = cursor.fetchall()

Try this one. Hopefully it works for you.

Salman Ahmed
  • 682
  • 1
  • 10
  • 24