python - 属性错误 : 'tuple' object has no attribute 'encode' - MySQLdb Python

标签 python mysql pycharm encode mysql-python

我正在用 MySQL 编写 Python 代码。

我的数据库架构如下:

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

以下是我的部分代码:

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。

出现以下错误:

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

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

最佳答案

查询参数应作为第二个参数传递给 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 占位符周围加上单引号 - 如果需要,数据库驱动程序会根据查询参数类型自动放置它们。

关于python - 属性错误 : 'tuple' object has no attribute 'encode' - MySQLdb Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35352283/

相关文章:

docker - 启动容器进程导致 "exec:\"uwsgi\": executable file not found in $PATH": unknown

python - 每次打印时覆盖打印行以实现时间算法

python - 在 Python 中创建没有变量 "x in"(例如范围)的生成器表达式或列表理解

django - 如何从PyCharm在远程主机上运行deploy命令?

mysql - 两个不同表上的 GROUP_CONCAT

java - 如何在我的 Gradle 构建中添加 JDBC MySQL 连接器?

python - 为什么 PyCharm 不允许在方法命名中使用大写字母?

python - 如何从列表中获取特定索引左侧的 x 项,包括 0 项

python - 如何在 python 中获取 JSON 的字段特定值?

php - 在没有 Cron 作业的情况下创建计划任务