It may be a bit hacked and not technically create a temporary table, it just acts as one, but you can create the @contextmanager decorator to create the table when the context opens and close it when it is closed. It might look something like this:
from contextlib import contextmanager import numpy as np import sqlalchemy as sqla import pandas as pd @contextmanager def temp_table(frame, tbl, eng, *args, **kwargs): frame.to_sql(tbl, eng, *args, **kwargs) yield eng.execute('DROP TABLE {}'.format(tbl)) df = pd.DataFrame(np.random.randint(21, size=(10, 10))) cnx = sqla.create_engine(conn_string) with temp_table(df, 'some_table_name', cnx, if_exists='replace', flavor='mysql', index=False):
I tested it with Teradata and it works great. I don't have MySQL around which I can test it, but as long as DROP statements work in MySQL, they should work as intended.
source share