You can qualify table names with the names of databases. For example, if you specify a database db1
when you establish the connection to the server, but you want to execute a query involving a table in another database db2
, simply do something like:
conn = MySQLdb.connect(host='localhost', user='root', db='db1')
c = conn.cursor()
c.execute("SELECT * FROM foo JOIN db2.bar")
Note also that it's not the case that you need to specify a database when setting up a connection. If you do omit the database, you need to qualify every table name with the name of a database:
conn = MySQLdb.connect(host='localhost', user='root')
c = conn.cursor()
c.execute("SELECT * FROM db1.foo JOIN db2.bar")