1

I am working in Python and have to use 2 databases on same servers. Inside my Python code, I am using SQL query to join 2 tables from above 2 databases. How can I accomplish that?

e.g. current code with 1 database connection

import pandas as pd
import psycopg2
import sys
import csv
from configobj import ConfigObj

config = ConfigObj('/home/configs/name.ini')


connect_string = """dbname=%s user=%s host=%s password=%s port = %s""" % (config.get('dbname'),config.get('user'), config.get('host'), config.get('password'), config.get('port'))

try:
    conn = psycopg2.connect(connect_string)
except:
    print("I am unable to connect to the database")

cur = conn.cursor()
David Buck
  • 3,752
  • 35
  • 31
  • 35
Deepika
  • 23
  • 3
  • 2
    If the tables are small enough, bring them all into local memory in a df. Otherwise the DB engine might be able to connect and you'd do it all in SQL - e.g. if using SQL Server can set up other DB's as "Linked Server" and then can join as if local table. – mgrollins Nov 13 '19 at 17:36
  • Please [note](https://stackoverflow.com/a/13452357/1422451): The new `.format()` method is meant to replace the old `%` formatting syntax. The latter has been de-emphasised, (but not officially deprecated *yet*). – Parfait Nov 13 '19 at 19:50
  • In PostgreSQL you would use [foreign data wrapper](http://www.postgresql.org/docs/current/interactive/postgres-fdw.html) or [dblink](http://www.postgresql.org/docs/9.3/static/contrib-dblink-function.html). See answers: [here](https://stackoverflow.com/questions/4678862/joining-results-from-two-separate-databases) and [here](https://stackoverflow.com/questions/46324/possible-to-perform-cross-database-queries-with-postgresql). – Parfait Nov 13 '19 at 20:03

0 Answers0