使用SQLAlchemy连接两个数据库中的表

2024-10-06 14:01:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用两个MySQL数据库。我想在SQLAlchemy中将DB 1中的一个表与DB2中的表连接起来。在

我正在使用automap_base,同时在sqlalchemy中创建数据访问层,如下所示。。。在

class DBHandleBase(object):

    def __init__(self, connection_string='mysql+pymysql://root:xxxxxxx@localhost/services', pool_recycle=3600):
            self.Base_ = automap_base()
            self.engine_ = create_engine(connection_string,
                                         pool_recycle = pool_recycle)
            self.Base_.prepare(self.engine_, reflect=True)
            self.session_ = Session(self.engine_)

我的桌子课就像

^{pr2}$

我是这样做的

db1_handle = DB1_Handle()
db2_handle = DB2_Handle()
t1d1_repo = T1D1_Repo(handle)
t1d2_repo = T1D2_Repo(person_handle)

result = t1d1_repo.session_.query(
            t1d1_repo.Table_,
            t1d2_repo.Table_).join(t1d2_repo.Table_, (
                t1d1_repo.Table_.person_id
                == t1d2_repo.Table_.uuid))

我得到这样的错误:

sqlalchemy.exc.ProgrammingError: (pymysql.err.ProgrammingError) (1146, "Table 'db1.t1d2' doesn't exist") [SQL: 'SELECT 

我们在数据库db1中创建了表t1,在数据库db2中创建了表t2。在

在sqlalchemy ORM中,可以跨两个数据库表进行连接吗? 如何做到这一点?在


Tags: self数据库basesqlalchemytablerepoenginehandle
1条回答
网友
1楼 · 发布于 2024-10-06 14:01:07

在MySQL中databases are synonymous with schemas。例如,在Postgresql中,您可以在一个数据库中的多个模式之间进行查询,但不能在数据库之间(直接地)进行查询,因此可以在MySQL中查询多个数据库,因为两者之间没有区别。在

因此,在MySQL中解决多数据库查询的一个可能的解决方案是使用一个引擎、会话和基来处理模式,并将^{} keyword argument传递给表,或者反映这两个模式,以便它们完全限定。在

由于没有您的数据,我在一个名为sopython和sopython2的测试服务器上创建了2个模式(MySQL数据库):

mysql> create database sopython;
Query OK, 1 row affected (0,00 sec)

mysql> create database sopython2;
Query OK, 1 row affected (0,00 sec)

并在每个表中添加了一个表:

^{pr2}$

在Python中:

In [1]: from sqlalchemy import create_engine

In [2]: from sqlalchemy.orm import sessionmaker

In [3]: from sqlalchemy.ext.automap import automap_base

In [4]: Session = sessionmaker()

In [5]: Base = automap_base()

在不指定默认情况下使用的架构(数据库)的情况下创建引擎:

In [6]: engine = create_engine('mysql+pymysql://user:pass@:6603/')

In [7]: Base.prepare(engine, reflect=True, schema='sopython')

In [8]: Base.prepare(engine, reflect=True, schema='sopython2')
/home/user/SO/lib/python3.5/site-packages/sqlalchemy/ext/declarative/clsregistry.py:120: SAWarning: This declarative base already contains a class with the same class name and module name as sqlalchemy.ext.automap.foo, and will be replaced in the string-lookup table.
  item.__name__

这个警告是我不完全理解的,可能是由于两个表之间的外键引用导致foo重新反射的结果,但它似乎没有引起麻烦。在


该警告是第二次调用prepare()重新创建和替换第一次调用中反映的表的类的结果。避免这一切的方法是首先使用元数据从两个模式中反映表,然后准备:

Base.metadata.reflect(engine, schema='sopython')
Base.metadata.reflect(engine, schema='sopython2')
Base.prepare()

在所有这些之后,您可以查询连接foo和bar:

In [9]: Base.metadata.bind = engine

In [10]: session = Session()

In [11]: query = session.query(Base.classes.bar).\
    ...:     join(Base.classes.foo).\
    ...:     filter(Base.classes.foo.name == 'heh')

In [12]: print(query)
SELECT sopython2.bar.bar_id AS sopython2_bar_bar_id, sopython2.bar.foo_id AS sopython2_bar_foo_id 
FROM sopython2.bar INNER JOIN sopython.foo ON sopython.foo.foo_id = sopython2.bar.foo_id 
WHERE sopython.foo.name = %(name_1)s

In [13]: query.all()
Out[13]: [<sqlalchemy.ext.automap.bar at 0x7ff1ed7eee10>]

In [14]: _[0]
Out[14]: <sqlalchemy.ext.automap.bar at 0x7ff1ed7eee10>

In [15]: _.foo
Out[15]: <sqlalchemy.ext.automap.foo at 0x7ff1ed7f09b0>

相关问题 更多 >