Pandas将表写入MySQL:“无法回滚”

2024-05-13 21:32:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要帮助才能工作。我有一个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

Tags: tonameimportdfdbsqlifexists
3条回答

对我来说这是用

MySQLdb.connect("127.0.0.1","root","","db" )

而不是

MySQLdb.connect("localhost","root","","db" )

然后

df.to_sql('df',sql_cnxn,flavor='mysql',if_exists='replace', chunksize=100)

使用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)

我能解决这个问题。我试图将一个大表加载到MySQL中,结果得到了错误。一个简单的for循环将数据分块上传解决了这个问题!非常感谢所有回复的人。

相关问题 更多 >