1

The following program collects the users inputs and stores them, then it saves that data to a .csv or emails it to me, then finally it 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 Answer 1

3

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))
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much, I have made the changes and it works perfectly. Such a small changes makes all the difference. I will look into this in the future! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.