AttributeError:“元组"对象没有属性“编码"-MySQLdb Python [英] AttributeError: 'tuple' object has no attribute 'encode' - MySQLdb Python

查看:63
本文介绍了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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆