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

2024-07-08 15:38:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图将子查询中的数据从postgres(from_engine)复制到sqlite数据库。我可以通过使用以下命令复制表来实现此目的:

smeta = MetaData(bind=from_engine)
table = Table(table_name, smeta, autoload=True)
table.metadata.create_all(to_engine)

但是,我不知道如何实现子查询语句的相同功能。

-桑德普

编辑: 继续回答。创建表后,我要按如下方式创建子查询stmt:

table = Table("newtable", dest_metadata, *columns)
stmt = dest_session.query(table).subquery();

然而,最后一个stmt以错误结束 cursor.execute(语句、参数) sqlalchemy.exc.ProgrammingError:(ProgrammingError)关系“newtable”不存在 第3行:来自newtable)作为anon_1


Tags: 数据fromtablepostgres语句enginedestmetadata
2条回答

至少在某些情况下是这样的:

  1. 使用查询对象的column_descriptions获取有关结果集中列的一些信息。

  2. 有了这些信息,您可以构建架构,以便在另一个数据库中创建新表。

  3. 在源数据库中运行查询并将结果插入到新表中。

首先为示例设置:

from sqlalchemy import create_engine, MetaData, 
from sqlalchemy import Column, Integer, String, Table
from sqlalchemy.ext.declarative import declarative_base
from 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 data
Base = 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()

有趣的是:

# 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 database
table.create(dest_engine)

# Finally execute the query
destSession = DestSession()
for row in query:
    destSession.execute(table.insert(row))
destSession.commit()

应该有更有效的方法来完成最后一个循环。但批量插入是另一个话题。

您还可以查看pandas数据帧。例如,方法将使用pandas.read_sql(query, source.connection)df.to_sql(table_name, con=destination.connection)

相关问题 更多 >

    热门问题