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

时间:2017-12-01 10:07:07

标签: python sql-server sqlalchemy

我在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"
)

1 个答案:

答案 0 :(得分:2)

您需要的是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