2017-06-15 55 views
1

我正在使用两个MySQL数据库。我想从SQL 1中的DB2中的表中加入一个表。使用SQLAlchemy在两个数据库中加入表格

我使用automap_base而在SQLAlchemy中创建数据访问层如下...

class DBHandleBase(object): 

    def __init__(self, connection_string='mysql+pymysql://root:[email protected]/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_) 

而且我的表类是像

class T1D1_Repo(): 


    def __init__(self, dbHandle): 
     # create a cursor 
     self.Table_ = dbHandle.Base_.classes.t1 
     self.session_ = dbHandle.session_ 

我提出了加入这个样子,

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和数据库db2的表t2中创建了表t1。

在sqlalchemy ORM中是否可以跨两个数据库表进行连接? 如何实现这一目标?

+0

这是不可能的(ish)。例如,您不能针对db1激发SQL查询,并期望它能够在db2中查询表。你必须单独查询这些表,并用Python“结合”结果。现在,如果您使用支持外部表的数据库,则可以将数据库链接在一起,并将其他数据库中的表作为外部表引入。但我不知道MySQL是否支持。 –

+0

相关:https://stackoverflow.com/questions/1565993/oracle-database-link-mysql-equivalent和https://stackoverflow.com/questions/9416871/qualifying-table-names-with-database-names-in -sqlalchemy。前面评论中的“不可能”有点强烈。 MySQL允许你在数据库之间进行查询,如果它们驻留在同一台服务器上,那么就是FEDERATED存储引擎。 –

+0

你的数据库在同一台服务器上吗? –

回答

1

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

有鉴于此,您在MySQL中的多数据库查询的可能解决方案可能是使用单个引擎,会话和Base来处理两个模式,并将schema 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) 

,并加入每一个表:

mysql> use sopython 
Database changed 
mysql> create table foo (foo_id integer not null auto_increment primary key, name text); 
Query OK, 0 rows affected (0,05 sec) 

mysql> insert into foo (name) values ('heh'); 
Query OK, 1 row affected (0,01 sec) 

mysql> use sopython2 
Database changed 
mysql> create table bar (bar_id integer not null auto_increment primary key, foo_id integer, foreign key (foo_id) references `sopython`.`foo` (foo_id)) engine=InnoDB; 
Query OK, 0 rows affected (0,07 sec) 

mysql> insert into bar (foo_id) values (1); 
Query OK, 1 row affected (0,01 sec) 

在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() 

没有指定其架构(数据库)创建引擎,你通过使用DEFA ULT:

In [6]: engine = create_engine('mysql+pymysql://user:[email protected]: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__ 

警告是我不完全理解,并且很可能是2个表之间的外键引用造成再反射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> 
+0

谢谢@Ilja Everila,听起来像一个有趣的解决方案。我一定会尝试一下。 –

相关问题