【问题标题】:How to use sqlAlchemy table shema to load data如何使用 sqlAlchemy 表模式加载数据
【发布时间】:2017-07-14 05:35:54
【问题描述】:

我有两个脚本schema.pyload_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


    【解决方案1】:

    试试from schema import *,它从一个模块中导入所有成员。有关import schemafrom schema import x 之间的区别,另请参阅these answers

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-19
      • 2013-07-01
      • 2013-05-27
      • 2018-05-22
      • 2019-12-10
      • 2022-08-13
      • 1970-01-01
      • 2023-03-09
      相关资源
      最近更新 更多