【问题标题】:AttributeError: 'tuple' object has no attribute 'encode' - MySQLdb PythonAttributeError:“元组”对象没有属性“编码”-MySQLdb Python
【发布时间】:2016-05-22 23:50:51
【问题描述】:

我正在用 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' 对象没有属性 'encode'

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

【问题讨论】:

    标签: python mysql pycharm encode mysql-python


    【解决方案1】:

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

    【讨论】:

    • 感谢您的帮助@alecxe .. 错误已解决。但现在它说:'builtin_function_or_method' 对象没有属性'decode'
    • @KreenaMehta cursor.execute(query, (id, )) 怎么样?
    猜你喜欢
    • 1970-01-01
    • 2020-12-04
    • 2017-12-08
    • 2013-06-21
    • 1970-01-01
    • 2021-09-11
    • 1970-01-01
    • 2015-04-22
    相关资源
    最近更新 更多