Skip to content

Instantly share code, notes, and snippets.

@iamnimnul
Forked from pawl/copy_table.py
Created August 28, 2020 13:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iamnimnul/b6ea51051d907c10c84d7e33942a7e3c to your computer and use it in GitHub Desktop.
Save iamnimnul/b6ea51051d907c10c84d7e33942a7e3c to your computer and use it in GitHub Desktop.
Copy Schema Of A Remote Database Table To A New Local Table With SQLalchemy
from sqlalchemy import create_engine, Table, Column, Integer, Unicode, MetaData, String, Text, update, and_, select, func, types
# create engine, reflect existing columns, and create table object for oldTable
srcEngine = create_engine('mysql+mysqldb://username:password@111.111.111.111/database') # change this for your source database
srcEngine._metadata = MetaData(bind=srcEngine)
srcEngine._metadata.reflect(srcEngine) # get columns from existing table
srcTable = Table('oldTable', srcEngine._metadata)
# create engine and table object for newTable
destEngine = create_engine('mysql+mysqldb://username:password@localhost/database') # change this for your destination database
destEngine._metadata = MetaData(bind=destEngine)
destTable = Table('newTable', destEngine._metadata)
# copy schema and create newTable from oldTable
for column in srcTable.columns:
destTable.append_column(column.copy())
destTable.create()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment