I'm using the Python3 version of the mysql-connector and I try to use the executemany function.
My code looks like this:
database = mysql.connector.connect(
host='localhost',
user='user',
password='test',
database='test_database'
)
cursor = database.cursor()
categories = ['Test1', 'Test 2']
stmt = "INSERT INTO categories (name) VALUES (%s)"
cursor.executemany(stmt, categories)
My table has just one column and this is a string column called name.
I tried to use the entries in the list as tuple, I changed the insert statement to this:
stmt = "INSERT INTO categories (name) VALUES ('%s')"
So I basically added single quotes in the %s placeholder. I also tried to replace the %s with ? but that also didn't work.
Due to the Python3 formatting conventions the single execute function is working when I use this:
stmt = "INSERT INTO categories (name) VALUES ('{}')".format('Test1')
Unfortunately the executemany function needs a second argument so I can't use the .format function.
This is my working example with the normal execute function:
database = mysql.connector.connect(
host='localhost',
user='user',
password='test',
database='test_database'
)
cursor = database.cursor()
categories = ['Test1', 'Test2']
for category in categories:
cursor.execute("INSERT INTO categories (name) VALUES ('{}')".format(category))
database.commit()
Edit:
I've read the official documentation. I copy and pasted the code and changed it to my parameters but it still doesn't work.
categories = [('Test1'),('Test2'),]
stmt = "INSERT INTO categories (name) VALUES (%s)"
cursor.executemany(stmt, categories)