简体   繁体   中英

create a copy of all tables with its key and other constraints from sql-server database to another database

I try to copy the sql-server's table with its keys and other constraints through SQLAlchemy in python

`from sqlalchemy import *
DATABASE_CONN = f'mssql://@{SERVER}/{DATABASE}?driver={DRIVER}'

DATABASE_CONN2 = f'mssql://@{SERVER}/{DB2}?driver={DRIVER}'

engine = create_engine(DATABASE_CONN)

engine2 = create_engine(DATABASE_CONN2)

connection = engine.connect() connection2 = engine2.connect()

metadata = MetaData() table = Table('table_name', metadata, autoload=True, autoload_with=engine) table.create(engine2)

ERROR:

sqlalchemy.exc.NoSuchTableError: table_name

if i putting the specific table name instead of 'table_name' then it create that table in new databse but i have to do it for all table so any technique to resolve this issue and make the copy of all table with its keys and other constraint at one go.

You recreate all the table schema from one database in a second by reflecting the first into a metadata object and then creating the tables in the second:

meta = MetaData()
meta.reflect(engine)
meta.create_all(engine2)

It's possible to control precisely which tables get reflected - review the docs for Reflecting Database Objects and metadata.reflect .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM