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

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

你可能感兴趣的:(python pandas dataframe to_sql方法error及其解决)