我需要帮助才能正常工作。我有一个pd.DataFrame (df),我需要将其加载到MySQL数据库中。我不明白该错误消息的含义以及如何解决。

任何帮助将不胜感激。

这是我尝试的:

    import MySQLdb
    from pandas.io import sql

    #METHOD 1
    db=MySQLdb.connect(host="***",port=***,user="***",passwd="***",db="***")
    df.to_sql(con=db, name='forecast', if_exists='replace', flavor='mysql')
    ##Also tried
    sql.write_frame(df, con=db, name='forecast', if_exists='replace', flavor='mysql')

   **DatabaseError**: Execution failed on sql: SHOW TABLES LIKE %s
   (2006, 'MySQL server has gone away')
   unable to rollback


   #METHOD 2: using sqlalchemy
   from sqlalchemy import create_engine

   engine =   create_engine("mysql+mysqldb://**username***:**passwd**@***host***:3306/**dbname**")
   conn = engine.raw_connection()
   df.to_sql(name='demand_forecast_t', con=conn,if_exists='replace',    flavor='mysql',index=False, index_label='rowID')
   conn.close()

错误消息是:
**OperationalError**: DatabaseError: Execution failed on sql: SHOW TABLES LIKE %s
(2006, 'MySQL server has gone away') unable to rollback

最佳答案

使用 sqlalchemy 时,您应该传递引擎而不是原始连接:

engine = create_engine("mysql+mysqldb://...")
df.to_sql('demand_forecast_t', engine, if_exists='replace', index=False)

不推荐在没有 sqlalchemy 的情况下写入 MySQL(因此指定 flavor='mysql' )已被弃用。

当问题是您的框架太大而无法一次写入时,您可以使用 chunksize 关键字(请参阅 docstring )。例如:
df.to_sql('demand_forecast_t', engine, if_exists='replace', chunksize=10000)

关于python - Pandas 将表写入MySQL : "unable to rollback",我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29356076/

10-12 17:57
查看更多