python - 属性错误 : 'tuple' object has no attribute 'encode' when inserting data using mysql-connector

标签 python mysql python-3.x mysql-connector

下面的程序收集用户输入并存储它们,然后将数据保存到 .csv/通过电子邮件发送给我,最后将该数据插入 MySQL 数据库。

我正在为此使用 mysql.connector,但出现错误:

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

程序执行时。

这是代码,我认为问题在于试图插入数据库的数据类型,但我不能确定。

import mysql.connector

# ...

# Connect to MySQL Database and send user_input data to 'user' TABLE.
cnx = mysql.connector.connect(user='root', password='ash123', host='localhost', database='user_data_db')
cursor = cnx.cursor()

query = ("INSERT INTO user (user_id, first_name, last_name, age, postcode,  email_address)"
         "VALUES (%s, %s, %s, %s, %s, %s)", (user_id, firstname, lastname, age, postcode, email)) 

cursor.execute(query)
print("Executed Successfully")

cursor.close()
cnx.close()

最佳答案

除非它是 bytesbytearray 类型,否则 cursor.execute 期望第一个参数(SQL 查询)具有 编码 方法。 query 是一个 2 元组,元组没有该方法并且尝试访问它失败并返回 AttributeError

您可以解压query,以便将其元素用作cursor.execute 的位置参数:

cursor.execute(*query)
# = cursor.execute("INSERT INTO user (user_id, first_name, last_name, age, postcode, email_address)"
#                  "VALUES (%s, %s, %s, %s, %s, %s)", (user_id, firstname, lastname, age, postcode, email))

关于python - 属性错误 : 'tuple' object has no attribute 'encode' when inserting data using mysql-connector,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28112952/

相关文章:

Python Pandas : Two ways null values table

mysql - 如果 ID 重复,则显示数据并更改值

android - 原始查询不工作android

python-3.x - Python 3.9.8、hashlib 和 RIPEMD160

python - 执行 `setup.py test`时不安装依赖

python - 使用 islice 和多处理批量读取和处理大型文本文件

html - 在发送到 sql 服务器之前从 html 输入元素中提取值

python - 从已经定义的变量中打印颜色

html - 使用 python 解析 HTML 的奇怪结构——第二个版本

python - readline 的构建轮失败 - 在 OSX 上安装 Rekall 时