问题描述
以下程序收集用户输入并将其存储,然后将数据保存到.csv/通过电子邮件发送给我,最后将数据插入MySQL数据库.
The below program collects the users inputs and stores them, it then saves that data to a .csv / emails it to me and finally inserts that data into a MySQL database.
我为此使用mysql.connector,但是出现错误:
I am using mysql.connector for this, however I am getting the error:
AttributeError: 'tuple' object has no attribute 'encode'
程序执行时.
这是代码,我认为问题与试图插入数据库的数据类型有关,但我不确定.
Here is the code, I think the problem is to do with the type of data trying to be inserted into the database, but I cannot be sure.
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()
推荐答案
除非是bytes
或bytearray
类型,否则cursor.execute
期望第一个参数(SQL查询)具有encode
方法. query
是2元组,元组不具有该方法,并且尝试访问它失败,并显示AttributeError
.
Unless it's of the bytes
or bytearray
type, cursor.execute
expects the first argument (SQL query) to have the encode
method. query
is a 2-tuple, tuples do not have that method and attempts to access it fail with AttributeError
.
您可以解压缩query
以便将其元素用作cursor.execute
的位置参数:
You can unpack query
, in order to use its elements as positional arguments for 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))
这篇关于AttributeError:使用mysql-connector插入数据时,"tuple"对象没有属性"encode"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!