【问题标题】:How to join tables from two different databases using sqlalchemy expression language / sqlalchemy core?如何使用 sqlalchemy 表达式语言/sqlalchemy 核心连接来自两个不同数据库的表?
【发布时间】:2018-07-02 05:15:30
【问题描述】:

我正在使用 MySql。然而,我能够找到使用 sqlalchemy orm 但不使用表达式语言的方法。所以我专门寻找基于核心/表达式语言的解决方案。数据库位于同一台服务器上

这是我的连接的样子:

connection = engine.connect().execution_options(
schema_translate_map = {current_database_schema: new_database_schema})
engine_1=create_engine("mysql+mysqldb://root:user@*******/DB_1")
engine_2=create_engine("mysql+mysqldb://root:user@*******/DB_2",pool_size=5)

metadata_1=MetaData(engine_1)
metadata_2=MetaData(engine_2)

metadata.reflect(bind=engine_1)
metadata.reflect(bind=engine_2)

table_1=metadata_1.tables['table_1']
table_2=metadata_2.tables['table_2']
query=select([table_1.c.name,table_2.c.name]).select_from(join(table_2,table_1.c.id==table_2.c.id,'left')

result=connection.execute(query).fetchall()

但是,当我尝试连接来自不同数据库的表时,它显然会引发错误,因为该连接属于其中一个数据库。而且我还没有尝试过其他任何事情,因为我找不到解决这个问题的方法。 提出问题的另一种方式(也许)是“如何使用 sqlalchemy 核心中的单个连接连接到多个数据库”。

【问题讨论】:

  • 该解决方案似乎不起作用。使用元数据访问表时引发键错误。

标签: python mysql sqlalchemy cross-database


【解决方案1】:

仅将here 的解决方案应用于Core,您可以创建一个连接到您的服务器的Engine 对象,但无需默认使用一个数据库:

engine = create_engine("mysql+mysqldb://root:user@*******/")

然后使用单个MetaData 实例反映每个架构的内容:

metadata = MetaData(engine)
metadata.reflect(schema='DB_1')
metadata.reflect(schema='DB_2')

# Note: use the fully qualified names as keys
table_1 = metadata.tables['DB_1.table_1']
table_2 = metadata.tables['DB_2.table_2']

您也可以使用其中一个数据库作为“默认”并在 URL 中传递它。在这种情况下,您将照常反映该数据库中的表,并仅在反映其他数据库时传递 schema= 关键字参数。

使用创建的引擎执行查询:

query = select([table_1.c.name, table_2.c.name]).\
    select_from(outerjoin(table1, table_2, table_1.c.id == table_2.c.id))

with engine.begin() as connection:
    result = connection.execute(query).fetchall()

【讨论】:

  • 嗨。这一切都很新。请问您是否错过了反映元数据和构建查询之间的任何步骤?为什么不使用Base = automap_base(metadata=metadata)Base.prepare()
猜你喜欢
  • 2016-06-24
  • 1970-01-01
  • 2017-05-21
  • 1970-01-01
  • 2021-09-09
  • 2021-02-10
  • 2015-10-26
  • 2023-03-11
  • 1970-01-01
相关资源
最近更新 更多