AttributeError: 'tuple' object does not have 'encode' attribute - MySQLdb Python

I am writing Python code with MySQL.

The schema of my database is as follows:

-------------
| id | name |
-------------
|    |      |
|    |      |

The following is part of my code:

cursor = self.conn.cursor()
query = ("SELECT name FROM TABLENAME WHERE id = '%s'", (str(id.decode('unicode_escape').encode('ascii', 'utf-8'),)))
cursor.execute(query)

I am passing the id from the url.

And getting the following error:

AttributeError: object 'tuple' does not have attribute 'encode'

I get results when I hardcode the valud identifier in the request. But for some reason, it does not work when I pass the parameter.

+4
source share
1 answer

Request parameters should be passed as the second parameter to execute():

cursor = self.conn.cursor() 
query = "SELECT name FROM TABLENAME WHERE id = %s"
cursor.execute(query, (str(id.decode('unicode_escape').encode('ascii', 'utf-8')), ))

, %s placeholder - .

+1

Source: https://habr.com/ru/post/1628401/


All Articles