executemany for MySQLdb error for large number of rows

∥☆過路亽.° 提交于 2019-12-10 10:14:40

问题


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?


回答1:


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




回答2:


sql ='SET GLOBAL max_allowed_packet=500*1024*1024'
cursor.execute(sql)


来源:https://stackoverflow.com/questions/13291700/executemany-for-mysqldb-error-for-large-number-of-rows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!