SqlAlchemy: export table to new database

前端 未结 2 747
甜味超标
甜味超标 2021-01-18 13:02

Only recently started using python, and I like it! However, I am stuck with SqlAlchemy.

I am trying to write a script that reads an MS SQL database, query a table (a

相关标签:
2条回答
  • 2021-01-18 13:35

    Test this:

    def copy_table(src_session, src_class, dst_session, dst_class):
        r=src_session.query(src_class).all()
        for i in r:
            j=dst_class()
            [setattr(j, col.name, getattr(i, col.name)) for col in i.__table__.columns]
            dst_session.add(j)
    
    se1=db1.Session()
    se2=db2.Session()
    copy_table(se1, db1.Book, se2, db2.Book)
    se2.commit()
    
    0 讨论(0)
  • 2021-01-18 13:38

    See Creating and Dropping Database Tables:

    Creating … individual tables can be done via the create() … method of Table.

    For reading the source structure, see Reflecting Database Objects:

    A Table object can be instructed to load information about itself from the corresponding database schema object already existing within the database.
    […]
    The reflection system can also reflect views.

    0 讨论(0)
提交回复
热议问题