Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas Write table to MySQL: "unable to rollback"

I need help to get this working. I have a pd.DataFrame (df), which I need to load to a MySQL database. I don't understand what the error message means and how to fix it.

Any help will be highly appreciated.

This is what I tried:

    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()

The error message is:

**OperationalError**: DatabaseError: Execution failed on sql: SHOW TABLES LIKE %s
(2006, 'MySQL server has gone away') unable to rollback
like image 387
Amrita Sawant Avatar asked Mar 30 '15 20:03

Amrita Sawant


1 Answers

When using sqlalchemy, you should pass the engine and not the raw connection:

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

Writing to MySQL without sqlalchemy (so with specifying flavor='mysql') is deprecated.

When the problem is that you have a too large frame to write at once, you can use the chunksize keyword (see the docstring). Eg:

df.to_sql('demand_forecast_t', engine, if_exists='replace', chunksize=10000)
like image 144
joris Avatar answered Jan 18 '23 17:01

joris