AttributeError: #39;tuple#39; object has no attribute #39;encode#39; - MySQLdb Python(AttributeError:“元组对象没有属性“编码-MySQLdb Python)
问题描述
我正在用 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.
这篇关于AttributeError:“元组"对象没有属性“编码"-MySQLdb Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:AttributeError:“元组"对象没有属性“编码"-MySQLdb Python
基础教程推荐
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- 在 SQL 中连接多个表 2021-01-01
- 无法解决整理冲突 2021-01-01
- 是否可以执行按位分组功能? 2021-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
