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

点点圈 提交于 2019-12-09 20:56:19

问题


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.

I am using mysql.connector for this, however I am getting the error:

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

when the program executes.

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()

回答1:


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.

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))


来源:https://stackoverflow.com/questions/28112952/attributeerror-tuple-object-has-no-attribute-encode-when-inserting-data-usi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!