Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python MySQLdb- using multiple database tables in query

I am writing a script in Python and I am using MySQLdb package.

 con1 = mdb.connect('127.0.0.1', 'root', '', 'teacher') 
 con2 = mdb.connect('127.0.0.1', 'root', '', 'student', true) 

I can execute a query using a single cursor in python. But I want to write query to use tables from both the database at once. How can I do that?

like image 644
Nirupam Dutta Purkayastha Avatar asked Sep 17 '25 14:09

Nirupam Dutta Purkayastha


1 Answers

Was looking for an answer to the same question. Found that connecting without specifying the database will allow you to query multiple tables:

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

Then you can query different tables from different databases:

select table1.field1,
       table2.field2
from database1.table1 inner join
     database2.table2 on database2.table2.join_field = database1.field1.join_field

And boom goes the dynamite

like image 137
kbuilds Avatar answered Sep 21 '25 18:09

kbuilds