如何连接SqlAlchemy以访问多个数据库服务器(来自不同的服务器)

时间:2019-06-18 22:10:15

标签: python database postgresql sqlalchemy

我正在尝试将来自不同架构的多个表连接到一个表中 用Python查询吗?

我为每个conn创建了单独的变量 变量connections,但错误显示了来自 不同的服务器不存在,但实际上存在。

import pandas as pd
from sqlalchemy import create_engine
import sqlite3
#import MySQLdb as mdb
#import pymysql as mdb
POSTGRES_ADDRESS1 = 'XXX'
POSTGRES_ADDRESS2 = 'XXX'
POSTGRES_PORT1 = 'XXX'
POSTGRES_PORT2 = 'XXX'
POSTGRES_USERNAME1 = 'XXX'
POSTGRES_USERNAME2 = 'XXX'
POSTGRES_PASSWORD1 = 'XXX'
POSTGRES_PASSWORD2 = 'XXX'
POSTGRES_DBNAME1 = 'db1( this db from Server A')
POSTGRES_DBNAME2 = 'db2(this db from Server B')
connections = {
'conn1' : create_engine('postgresql://{username}:{password}@{ipaddress}: 
{port}/{dbname}'.format(username=POSTGRES_USERNAME1, 
password=POSTGRES_PASSWORD1, ipaddress=POSTGRES_ADDRESS1, 
port=POSTGRES_PORT1, dbname=POSTGRES_DBNAME1)),
'conn2' : create_engine('postgresql://{username}:{password}@{ipaddress}: 
{port}/{dbname}'.format(username=POSTGRES_USERNAME2, 
password=POSTGRES_PASSWORD2, ipaddress=POSTGRES_ADDRESS2, 
port=POSTGRES_PORT2, dbname=POSTGRES_DBNAME2))
}    
#connections['conn1'].execute('SELECT col1 from schema1.table1 limit 
100')
query='''
select 
a.col1,
a.col2,
b.col1,
b.col4,
b.col5
from
server1.schema2.table2 a
inner join
server2.schema3.table3 b
on
a.col1= b.col1
'''
df= pd.read_sql_query(query,connections['conn1'])
df1= pd.read_sql_query(query,connections['conn2'])

Programming Error: (psycopg2.errors.UndefinedTable) relation 
"sgxpd003.table" does not exist
LINE 20: sgxpd003. table d

0 个答案:

没有答案