Amr*_*ant 7 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()
Run Code Online (Sandbox Code Playgroud)
错误消息是:
**OperationalError**: DatabaseError: Execution failed on sql: SHOW TABLES LIKE %s
(2006, 'MySQL server has gone away') unable to rollback
Run Code Online (Sandbox Code Playgroud)
jor*_*ris 14
使用sqlalchemy时,您应该传递引擎而不是原始连接:
engine = create_engine("mysql+mysqldb://...")
df.to_sql('demand_forecast_t', engine, if_exists='replace', index=False)
Run Code Online (Sandbox Code Playgroud)
不使用sqlalchemy写入MySQL(如此指定flavor='mysql'
)不推荐使用.
当问题是你有一个太大的框架可以一次写入时,你可以使用chunksize
关键字(参见docstring).例如:
df.to_sql('demand_forecast_t', engine, if_exists='replace', chunksize=10000)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
10050 次 |
最近记录: |