回答

收藏

SQLAlchemy-将子查询的架构和数据复制到另一个数据库

技术问答 技术问答 423 人阅读 | 0 人回复 | 2023-09-14

我正在尝试将子查询中的数据postgres(from_engine)复制到sqlite数据库。我可以使用以下命令复制表来实现这一目的:, d/ n3 ^* Y5 ?$ w! F9 w
smeta = MetaData(bind=from_engine)table = Table(table_name,smeta,autoload=True)table.metadata.create_all(to_engine)但是,我不确定如何为子查询句子实现相同的功能。+ B8 d  o# \$ e# W8 l# s
-山迪普' B/ n9 x8 p" b6 e! b
编辑:跟进答案。创建表后,我要创建一个子查询stmt,如下所示:* @0 H; z% _0 S) l( \2 n5 f
table = Table("newtable",dest_metadata,*columns)stmt = dest_session.query(table).subquery();但是,最后一个stmt最终出现了错误cursor.execute(statement,parameters)sqlalchemy.exc.ProgrammingError:(ProgrammingError)关系“
5 b( I  h5 _! o: Bnewtable第三行不存在:FROM newtable)AS anon_1
5 F* y# [2 y0 S7 p* C7 Z& ]                                                                % i8 H# U- b( c& l5 d
    解决方案:                                                                5 f  {3 s% b% c! R0 q: o
                                                                至少在某些情况下:2 g5 ^# f0 i( w
[ol]使用column_descriptions查询对象获取各列相关结果的信息。
$ i5 j3 V5 k! D1 ~: r/ F! X1 |利用这些信息,您可以在另一个数据库中构建创建新表的模式。
/ x# z- S# v: h: K( S6 p运行查询源数据库,并将结果插入新表。
; Q1 v5 c" y9 Z* x  x[/ol]先设置示例:
) i: f+ F$ F# \% N. ~, \from sqlalchemy import create_engine,MetaData,from sqlalchemy import Column,Integer,String,Tablefrom sqlalchemy.ext.declarative import declarative_basefrom sqlalchemy.orm import sessionmaker# Engine to the database to query the data from# (postgresql)source_engine = create_engine('sqlite:///:memory:',echo=True)SourceSession = sessionmaker(source_engine)# Engine to the database to store the results in# (sqlite)dest_engine = create_engine('sqlite:///:memory:',echo=True)DestSession = sessionmaker(dest_engine)# Create some toy table and fills it with some dataBase = declarative_base()class Pet(Base):    __tablename__ = 'pets'    id = Column(Integer,primary_key=True)    name = Column(String)    race = Column(String)Base.metadata.create_all(source_engine)sourceSession = SourceSession()sourceSession.add(Pet(name="Fido",race="cat"))sourceSession.add(Pet(name="Ceasar",race="cat"))sourceSession.add(Pet(name="Rex",race="dog"))sourceSession.commit()现在去有趣的地方:
/ g9 \7 N# A4 a( r6 i3 o$ e  c9 z) G8 f# This is the query we want to persist in a new table:query= sourceSession.query(Pet.name,Pet.race).filter_by(race='cat')# Build the schema for the new table# based on the columns that will be returned # by the query:metadata = MetaData(bind=dest_engine)columns = [Column(desc['name'],desc['type']) for desc in query.column_descriptions]column_names = [desc['name'] for desc in query.column_descriptions]table = Table("newtable",metadata,*columns)# Create the new table in the destination databasetable.create(dest_engine)# Finally execute the querydestSession = DestSession()for row in query:    destSession.execute(table.insert(row))destSession.commit()最后一个一个循环应该有更有效的方法。但批量插入是另一个主题。
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则