私は2つのスクリプトschema.py
とload_data.py
を持っています。 schema.py
では、sqlAlchemy Baseを使用して20を超えるテーブルのスキーマを定義します。テーブルの二つは、次のようになります。sqlAlchemyテーブルシーマを使用してデータをロードする方法
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)
私は別のデータベースからのもの〜20個のテーブルをコピーするために、私のload_data.py
を使用します。私の質問は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)