Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connect to two databases

Tags:

python

mysql

I want to connect to two databases using Python and, later on, use tables from both of the databases. How can I do this? Is the following code correct?

con = mdb.connect(host=MY_HOST, user=MY_USER, passwd=MY_PASS, db1=MY_DB1, db2=MY_DB2)
like image 974
manxing Avatar asked Jan 20 '12 11:01

manxing


2 Answers

If you don't specify the database in your connect call, you can write queries against multiple databases at once. The documentation says that db is not required.

db = _mysql.connect('localhost', 'user', 'passwd')

then

SELECT u.*, i.* FROM db1.users u LEFT JOIN db2.items i ON u.id = i.user_id

But it'll only work if the two databases are on the same server.

like image 92
greut Avatar answered Oct 05 '22 23:10

greut


Just make two separate connections

con1 = mdb.connect (host=MY_HOST, user=MY_USER, passwd=MY_PASS, db1=MY_DB1)
con2 = mdb.connect (host=MY_HOST2, user=MY_USER2, passwd=MY_PASS2, db2=MY_DB2)

and use them independently just as you would when using one database.

like image 28
Johan Lundberg Avatar answered Oct 06 '22 01:10

Johan Lundberg