python - Pandas 将表写入 MySQL : "unable to rollback"

标签 python mysql pandas

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

相关文章:

python - Pandas:在 df 中为包含列表值的分解列创建多行

python - 在 python 中连接失败后重试 SQL 连接的正确语法?

python - 在 Pandas 时间序列数据框中删除重复项

mysql - 重构多个表的连接

python - 在多维 Pandas DataFrame 中明智地获取最小列数 - Python

python - 如何将值从 Python Pandas 中的多个字典对象插入到数据帧中

python - 替换或删除 python 中的特定 unicode 字符

python - 随着维度的增加,多处理的 Numpy 矩阵乘法突然变慢

php - 将本地主机 joomla 站点转移到实时域数据库问题

Mysql 5.7不使用索引