Skip to content

Instantly share code, notes, and snippets.

@aeharvlee
Last active February 14, 2021 23:43
Show Gist options
  • Save aeharvlee/f399dcb42b5ece1f429f15b6b68b26f3 to your computer and use it in GitHub Desktop.
Save aeharvlee/f399dcb42b5ece1f429f15b6b68b26f3 to your computer and use it in GitHub Desktop.
schema = 'important_schema'
tbl_name = f'important_table'
tmp_tbl = f'{tbl_name}_TMP'
old_tbl = f'{tbl_name}_OLD'
try:
engine.execute(f'TRUNCATE TABLE {tmp_tbl}') # Make sure tmp table is empty
pandas_dataframe.to_sql(tmp_tbl, engine, schema, if_exists='append', index=False)
engine.execute(f'RENAME TABLE {tbl_name} TO {old_tbl}, {tmp_tbl} TO {tbl_name}, {old_tbl} TO {tmp_tbl}')
engine.execute(f'TRUNCATE TABLE {tmp_tbl}')
except Exception as e:
logging.error(e)
exit(1)
logging.debug(f'Finished inserting dataframe to {tbl_name}')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment