Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

executemany for MySQLdb error for large number of rows

I'm currently running a script to insert values (a list of tuples) into a MySQL database, using the execute many function. When I use a small number of rows (`1000), the script runs fine.

When I use around 40,000 rows, I receive the following errors:

cursor.executemany( stmt, trans_frame)
Traceback (most recent call last):
  File "C:\Python27\lib\site-packages\IPython\core\interactiveshell.py", line 2538, in run_code
    exec code_obj in self.user_global_ns, self.user_ns
  File "<ipython-input-1-66b44e71cf5a>", line 1, in <module>
    cursor.executemany( stmt, trans_frame)
  File "C:\Python27\lib\site-packages\MySQLdb\cursors.py", line 253, in executemany
    r = self._query('\n'.join([query[:p], ',\n'.join(q), query[e:]]))
  File "C:\Python27\lib\site-packages\MySQLdb\cursors.py", line 346, in _query
    rowcount = self._do_query(q)
  File "C:\Python27\lib\site-packages\MySQLdb\cursors.py", line 310, in _do_query
    db.query(q)
OperationalError: (2006, 'MySQL server has gone away')

Any suggestions?

like image 305
Matt Avatar asked Nov 08 '12 15:11

Matt


People also ask

What does executemany() method do?

executemany() Method. This method prepares a database operation (query or command) and executes it against all parameter sequences or mappings found in the sequence seq_of_params . In Python, a tuple containing a single value must include a comma.

What does the executemany method do mcq?

Answer: The executemany( ) function is used to insert multiple rows into a table.

How to insert multiple rows in sql using python?

To insert multiple rows into a table, use the executemany() method.


2 Answers

You could try setting the max_allowed_packet parameter just for one session:

sql ='SET SESSION max_allowed_packet=500M'
cursor.execute(sql)
sql = ...
args = ...
cursor.executemany(sql, args)

If this works, you could leave the code as it is, or change your my.cnf file (knowing that that solves the executemany problem).

like image 121
unutbu Avatar answered Sep 24 '22 15:09

unutbu


sql ='SET GLOBAL max_allowed_packet=500*1024*1024'
cursor.execute(sql)
like image 39
CurryChen Avatar answered Sep 23 '22 15:09

CurryChen