【发布时间】:2017-07-14 05:35:54
【问题描述】:
我有两个脚本schema.py 和load_data.py。在schema.py 中,我使用 sqlAlchemy Base 为 20 多个表定义了架构。其中两个表如下所示:
schema.py
Base = declarative_base()
meta = MetaData()
class Table1(Base):
__tablename__ = 'table1'
id = Column(Integer, primary_key=True)
name = Column(String)
class Table2(Base):
__tablename__ = 'table2'
id = Column(Integer, primary_key=True)
bdate = Column(Date)
...
class Table20(Base):
__tablename__ = 'table20'
id = Column(Integer, primary_key=True)
bdate = Column(Date)
我想使用我的load_data.py 将这大约 20 个表从一个数据库复制到另一个数据库。我的问题是如何使用我在schema.py 中定义的架构在load_data.py 中创建表??按照Introductory Tutorial of Python’s SQLAlchemy中的例子,我使用import来加载所有的表模式类,但是我觉得它太乱了。有没有更好的方法来处理这种情况???我是 sqlAlchemy 的新手,如果这个问题看起来太幼稚,请多多包涵。
load_data.py
from schema import Base, Table1, Table2, Table3, Table4, Table5, Table6, Table7, Table8, Table9, Table10,..., Table20
src_engine = create_engine('sqlite:// sqlite_test.db')
dst_engine = create_engine('postgresql:///postgresql_test.db')
Base.metadata.create_all(dst_engine)
tables = Base.metadata.tables
for tbl in tables:
data = src_engine.execute(tables[tbl].select()).fetchall()
for a in data: print(a)
if data:
dst_engine.execute( tables[tbl].insert(), data)
【问题讨论】:
标签: python sqlalchemy schema