gpt4 book ai didi

python - 如何在 SQLAlchemy 中进行跨数据库查询连接?

转载 作者:太空狗 更新时间:2023-10-30 01:19:19 31 4
gpt4 key购买 nike

我在 SQLAlchemy 中找不到这个简单查询的解决方案示例。 SQLAlchemy能否替代T-SQL ETL数据修改?

select a.field1, a.field2, b.field2
from database1.schema1.table_a as a
inner join database2.schema1.table_b as b
on a.fileld1 = b.fileld1

我将此连接与 Windows 身份验证结合使用:

engine = create_engine(
"mssql+pyodbc://@{Server}/{database}?driver=SQL+Server?trusted_connection=yes"
)

最佳答案

你需要的是multipart schema names .那和使用 __table_args__ – 如果您使用的是声明式 – 将允许您执行查询。由于您省略了表或模型定义,我将根据您的查询示例生成示例:

In [8]: class TableA(Base):
...: __tablename__ = 'table_a'
...: __table_args__ = {
...: 'schema': 'database1.schema1'
...: }
...: id = Column(Integer, primary_key=True)
...: field1 = Column(Integer)
...: field2 = Column(Integer)
...:

In [9]: class TableB(Base):
...: __tablename__ = 'table_b'
...: __table_args__ = {
...: 'schema': 'database2.schema1'
...: }
...: id = Column(Integer, primary_key=True)
...: field1 = Column(Integer)
...: field2 = Column(Integer)
...:

In [10]: q = session.query(TableA.field1, TableA.field2, TableB.field2).\
...: join(TableB, TableA.field1 == TableB.field1)

In [12]: q.statement.compile(dialect=mssql.dialect())
Out[12]: <sqlalchemy.dialects.mssql.base.MSSQLCompiler at 0x7fa3886027b8>

In [13]: print(_)
SELECT database1.schema1.table_a.field1, database1.schema1.table_a.field2, database2.schema1.table_b.field2
FROM database1.schema1.table_a JOIN database2.schema1.table_b ON database1.schema1.table_a.field1 = database2.schema1.table_b.field1

关于python - 如何在 SQLAlchemy 中进行跨数据库查询连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47590982/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com