AttributeError: 'tuple' object has no attribute 'encode' when inserting data using mysql-connector

AttributeError: 'tuple' object has no attribute 'encode' when inserting data using 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 查询)具有 encode 方法。 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))