AttributeError:“元组"对象没有属性“编码"-MySQLdb Python

2022-01-08 00:00:00 python mysql-python pycharm encode mysql

我正在用 MySQL 编写 Python 代码.

I am writing a Python code with MySQL.

我的数据库架构如下:

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

以下是我的代码的一部分:

Following is a 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)

我从 URL 传递 ID.

I am passing the ID from the URL.

并得到以下错误:

AttributeError: 'tuple' 对象没有属性 'encode'

AttributeError: 'tuple' object has no attribute 'encode'

当我在查询中硬编码 ID 的值时,我得到了结果.但是由于某种原因,当我传入参数时它不起作用.

I get the results when I hard-code the valud of ID in the query. But for some reason it is not working when I pass in a parameter.

推荐答案

查询参数应该作为第二个参数传递给execute():

The query parameters should be passed as a 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 占位符周围加上单引号 - 如果需要,数据库驱动程序会根据查询参数类型自动放置它们.

Note that you don't need the single quotes around the %s placeholder - the database driver would put them automatically if needed depending on the query parameter type.

相关文章