0
我有兩個腳本schema.py
和load_data.py
。在schema.py
中,我使用sqlAlchemy Base爲超過20個表定義了模式。表中的兩個樣子:如何使用sqlAlchemy table shema加載數據
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)