python - SqlAlchemy Python 多数据库

标签 python sqlalchemy

我正在使用 SqlAlchemy 访问多个数据库(在同一台服务器上)。我当前的连接字符串如下

connect_string = "mssql+pyodbc://{0}:{1}@{2}/{3}".format(USERNAME_R, PASSWORD_R, SERVER_R, DATABASE_R)
engine = create_engine(connect_string)
session = sessionmaker(bind=engine)()
Record = declarative_base(engine)

如何修改此声明以便能够连接到同一服务器上的多个数据库(例如 DATABASE1DATABASE2)。这似乎指向了正确的方向,但不是很清楚,我不确定它是否特定于 Flask:

https://pythonhosted.org/Flask-SQLAlchemy/binds.html

最佳答案

您好,您可以使用 follwing 来实现。

engines = {
    'drivers':create_engine('postgres://postgres:admin@localhost:5432/Drivers'),
    'dispatch':create_engine('postgres://postgres:admin@localhost:5432/dispatch')
}

我在服务器和两个表中有两个数据库。之后,您可以在进行查询时使用路由类为特定的数据库连接路由:

  class RoutingSession(Session):
    def get_bind(self, mapper=None, clause=None):
        if mapper and issubclass(mapper.class_, drivers):
            return engines['drivers']
        elif self._flushing:
            return engines['dispatch']

现在您可以相应地触发查询,例如,首先您需要使用这样的方式进行 session :

Session = sessionmaker(class_=RoutingSession)
session = Session()
driverssql = session.query(drivers).all()

这是你可以在 sqlalchemy 中使用多个数据库

关于python - SqlAlchemy Python 多数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28238785/

相关文章:

python - Python 日志记录中的准确时间戳

python - 导入 M2Crypto Mac OS X 时出错

python - Sqlalchemy 双关联表?

python - SQLAlchemy:将多个实例映射到同一行

mysql - 在 SQLAlchemy 中设计数据库架构时,我需要多久使用一次 "backrefs"?

python - 属性错误 : type object 'User' has no attribute 'query'

Python 图像库 : How to combine 4 images into a 2 x 2 grid?

python - 将所有列的信息混合在一个列中

python - 使用 jupyter lab 重新连接以远程运行内核

python - 为 windows 配置 sqlalchemy