Why is executemany slow in Python MySQLdb?

Your first example is a single (large) statement that is generated and then sent to the database.

The second example is a much simpler statement that inserts/replaces a single row but is executed multiple times. Each command is sent to the database separately so you have to pay the turnaround time from client to server and back for every row inserted. I would think that this extra latency introduced between the commands is the main reason for the decreased performance of the second example.


Try lowercasing the word 'values' in your query - this appears to be a bug/regression in MySQL-python 1.2.3.

MySQL-python's implementation of executemany() matches the VALUES clause with a regular expression and then just clones the list of values for each row of data, so you end up executing exactly the same query as with your first approach.

Unfortunately the regular expression lost its case-insensitive flag in that release (subsequently fixed in trunk r622 but never backported to the 1.2 branch) so it degrades to iterating over the data and firing off a query per row.