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