python pandas dataframe to_sql方法error及其解决

  今天遇到了一个问题,很是奇怪,自己也想了一个另类的方法将其解决了,现在将详细过程经过记录如下:

  我在处理完一个dataframe之后,需要将其写回到数据库。这个dataframe比较大,共有53列,72609行,使用下述代码尝试将其写入mysql数据库。

pd.io.sql.to_sql(df,'xxx',zh_con,flavor='mysql',if_exists='append',index=False)

  然后就报错了,错误如下:

Traceback (most recent call last):
  File "/home/fit/PycharmProjects/Decision_Tree_Rough_sets_theory/main/handle_data.py", line 33, in <module>
    pd.io.sql.to_sql(df,'A_stock_quarter_total',zh_con,flavor='mysql',if_exists='append',index=False)
  File "/home/fit/.pyenv/versions/2.7.11/lib/python2.7/site-packages/pandas/io/sql.py", line 569, in to_sql
    chunksize=chunksize, dtype=dtype)
  File "/home/fit/.pyenv/versions/2.7.11/lib/python2.7/site-packages/pandas/io/sql.py", line 1634, in to_sql
    table.insert(chunksize)
  File "/home/fit/.pyenv/versions/2.7.11/lib/python2.7/site-packages/pandas/io/sql.py", line 765, in insert
    self._execute_insert(conn, keys, chunk_iter)
  File "/home/fit/.pyenv/versions/2.7.11/lib/python2.7/contextlib.py", line 35, in __exit__
    self.gen.throw(type, value, traceback)
  File "/home/fit/.pyenv/versions/2.7.11/lib/python2.7/site-packages/pandas/io/sql.py", line 1525, in run_transaction
    self.con.rollback()
_mysql_exceptions.OperationalError: (2006, 'MySQL server has gone away')

  在互联网上没有找到任何解决方法,尝试将dataframe行数缩减,成功的写入了数据库。于是我想到利用循环分批次将数据写入数据库,如下:

l=0
r=100
length =len(df)
while(l<length):
    pd.io.sql.to_sql(df[l:r],'xxx',my_con,flavor='mysql',if_exists='append',index=False)
    l+=100
    r+=100

  问题成功解决!就是暂时不知道真实的错误原因,需要进一步探讨。

  今天再次遇到这个问题,google了一下,在stackoverflow上面找到了答案.可以通过指定chunksize参数的方式来进行大批量插入,pandas会自动将数据拆分成chunksize大小的数据块进行批量插入,其实原理类似于我在上面使用的循环插入法.在不指定这个参数的时候,pandas会一次性插入dataframe中的所有记录,mysql如果服务器不能响应这么大数据量的插入,就会出现上述错误.附上正确的插入姿势:

pd.io.sql.to_sql(df,'xxx',zh_con,flavor='mysql',if_exists='append',index=False,chunksize=10000)
#此处的chunksize可以自定义
原文地址:https://www.cnblogs.com/zhoudayang/p/5295511.html