This page may be out of date. Submit any pending changes before refreshing this page.
Hide this message.
Quora uses cookies to improve your experience. Read more

How can I connect to multiple databases in SQLAlchemy?

1 Answer
Just the same way you connect to one. Example:

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

db1 = create_engine('postgresql://user1:password1@host1/dbname1')
db2 = create_engine('mysql://user2:password2@host2/dbname2')
DB1Session = sessionmaker(db1)
DB2Session = sessionmaker(db2)
db1session = DB1Session()
db2session = DB2Session()

db1session.query(Whatever)...
db2session.query(AnythingElse)...

db2session.commit()
db1session.rollback()


The two engines, and the two session makers wrapping them, are distinct and independent, you can use them at will. SQLAlchemy does not care how many different databases you are talking to, simultaneously.

Your table metadata and mappers may be bound to an engine directly, MetaData(bind=someengine), so if you do reflection or table creation or such, you may need to specify the engine explicitly. E.g. to create the same table in two databases:

db1meta = MetaData(db1)
mytable = Table('mytable', db1meta, Column('id', Integer, primary_key=True))
mytable.create() # creates it in db1, the default for its metadata object
mytable.create(bind=db2) # creates it in db2, overriding the default
mytable.create(bind=db1session.connection())
# last line creates the table in db1 with transactional DDL
# (works in PostgreSQL), so the table creation will be rolled
# back if the transaction is rolled back.


See:

http://www.sqlalchemy.org/docs/c...
http://www.sqlalchemy.org/docs/c...
http://www.sqlalchemy.org/docs/o...
Your response is private.
Is this answer still relevant and up to date?