I am using SQLAlchemy to connect to write pandas DataFrame to MySQL database. At the beginning of my code, I create the SQLAlchemy mechanism:
engine = create_my_sqlalchemy_connection()
I do some queries, do some calculations, and then try to use the same engine to write to the database a bit later:
df.to_sql('my_table', engine, if_exists='append', index=False)
Sometimes this works, and sometimes the connection is lost by the time the code is ready to be written to the database, and there is an error.
I could try, except and if necessary create a new connection:
try: df.to_sql('my_table', engine, if_exists='append', index=False) except: engine = create_my_sqlalchemy_connection() df.to_sql('my_table', engine, if_exists='append', index=False)
However, I thought I would get to you and see if anyone knows a better way (for example, if there is some SQLAlchemy method that I donโt know about for testing to find out if the connection still exists).
source share