SQLAlchemy中的跨数据库连接

17 投票
1 回答
9664 浏览
提问于 2025-04-16 20:03

有没有办法在SQLAlchemy中进行跨数据库的连接查询?具体来说,这是我的使用场景:

数据库结构

  1. db1.entity1
    1. entity1_id: 主键
    2. entity2_id: 外键,指向 db2.entity2.entity2_id
  2. db2.entity2
    1. entity2_id: 主键

模型

我在模型中使用的是 声明式风格

class Entity1(Base):
  __tablename__ = 'entity1' ## I tried combination of <db>.<table> with no success
  entity1_id = Column(Integer, primary_key=True)
  entity2_id = Column(Integer, ForeignKey('db2.entity2.entity2_id'))
  entity2 = relationship('Entity2')

class Entity2(Base):
  __tablename__ = 'entity2' ## I tried combination of <db>.<table> with no success
  entity2_id = Column(Integer, primary_key=True)

现在,正如预期的那样,我对 Entity1 的查询失败了,MySQL 报错说找不到表 entity2。我尝试了很多不同的 __tablename__ 组合,但都没有成功。所以我在想,SQLAlchemy 中是否有可能做到这一点。

1 个回答

25

你可能需要把 schema 这个参数传给 sqlalchemy.schema.Table。当你使用声明式基类进行对象关系映射(ORM)时,可以通过你类里的 __table_args__ 属性来提供这个额外的参数。

class Entity2(Base):
    __tablename__ = 'entity2' ## I tried combination of <db>.<table> with no success
    __table_args__ = {'schema': 'db2'}
    entity2_id = Column(Integer, primary_key=True) 

class Entity1(Base):
    __tablename__ = 'entity1' ## I tried combination of <db>.<table> with no success
    __table_args__ = {'schema': 'db1'}
    entity1_id = Column(Integer, primary_key=True)
    entity2_id = Column(Integer, ForeignKey(Entity2.entity2_id))
    entity2 = relationship('Entity2')

撰写回答