Incorrect number of arguments executing prepared statement - Python / MySQL

Viewed 916

When executing the following code in order to insert multiple values through a variable from python into mysql, I get:

'Incorrect number of arguments executing prepared statement ' error after executing 'result = cursor.executemany(sql_insert_query, records_to_insert)'

if i remove 'prepared=True', the error becomes:

'Not all parameters were used in the SQL statement'

import mysql.connector
connection = mysql.connector.connect(host='localhost',
                         database='majorprediction',
                         user='root',
                         password='')
records_to_insert = [ ('x') ,
                     ('y'),
                     ('z') ]
sql_insert_query = """ INSERT INTO majorpred (Major) 
                   VALUES (%s) """
cursor = connection.cursor(prepared=True)
result  = cursor.executemany(sql_insert_query, records_to_insert)
connection.commit()

Can anyone specify where is the problem?

1 Answers

You are passing a list of characters instead of tuples. For instance, if you try and run:

for record in records_to_insert:
    print(record, isinstance(record, str), isinstance(record, tuple))

You will get:

x True False
y True False
z True False

To create tuples with a single element in python you can do the following:

records_to_insert = [
    ('x',),
    ('y',),
    ('z',) 
]

If you have a list of parameters and want to cast all of them to tuple you can do as follows:

list_of_elements = list("list_of_characters")
tuples = [
    tuple(e) for e in list_of_elements
]

Hope this helps!

Related