Ashley Redman Ashley Redman - 3 months ago 10
MySQL Question

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

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

Answer

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