Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SqlAlchemy Python multiple databases

I'm using SqlAlchemy to access multiple databases (on the same server). My current connection string is the following

connect_string = "mssql+pyodbc://{0}:{1}@{2}/{3}".format(USERNAME_R, PASSWORD_R, SERVER_R, DATABASE_R)
engine = create_engine(connect_string)
session = sessionmaker(bind=engine)()
Record = declarative_base(engine)

How do I modify this declaration to be able to connect to multiple databases on the same server (e.g. DATABASE1 & DATABASE2). It seems like this is pointing in the right direction, but it's not very clear and I'm not sure if it is specific to Flask:

https://pythonhosted.org/Flask-SQLAlchemy/binds.html

like image 803
Michael Avatar asked Jan 30 '15 15:01

Michael


People also ask

Is SQLAlchemy good for ETL?

One of the key aspects of any data science workflow is the sourcing, cleaning, and storing of raw data in a form that can be used upstream. This process is commonly referred to as “Extract-Transform-Load,” or ETL for short.

Is SQLAlchemy worth learning?

SQLAlchemy is the ORM of choice for working with relational databases in python. The reason why SQLAlchemy is so popular is because it is very simple to implement, helps you develop your code quicker and doesn't require knowledge of SQL to get started.

What is SQLAlchemy in Python?

Python has many ORM libraries you can use with SQLAlchemy being one of the most popular ones for relational databases. SQLAlchemy also works with many web frameworks including flask and databases, such as SQLite, MySQL, and Postgres. Let’s learn a little bit more about SQLAlchemy now. Why Use SQLAlchemy?

What makes SQLAlchemy different from other databases?

SQL databases behave less like object collections the more size and performance start to matter; object collections behave less like tables and rows the more abstraction starts to matter. SQLAlchemy aims to accommodate both of these principles. SQLAlchemy considers the database to be a relational algebra engine, not just a collection of tables.

What databases are supported by SQLAlchemy?

Supported Databases SQLAlchemy includes dialects for SQLite, Postgresql, MySQL, Oracle, MS-SQL, Firebird, Sybase and others, most of which support multiple DBAPIs. Other dialects are published as external projects. The corresponding DB-API 2.0 implementation (or sometimes one of several available) is required to use each particular database.

How does flask-SQLAlchemy work with SQLAlchemy?

In Flask-SQLAlchemy, on the other hand, binds are always engines. If there’s no bind specified, the default database will be the one configured in SQLALCHEMY_DATABASE_URI – just like in the example above. You can set up an arbitrary number of separate databases with SQLAlchemy.


2 Answers

Adding a bit more of insight, the official SQLAlchemy documentation now has a couple more strategies than the ones presented on the rest of the answers.

Just take a look at the following links:

  • Partitioning Strategies (e.g. multiple database backends per Session)
  • Session API - Session and sessionmaker() - 'binds' parameter
like image 134
Alejandro de Haro Avatar answered Oct 08 '22 12:10

Alejandro de Haro


Hi you can achieve this using follwing .

engines = {
    'drivers':create_engine('postgres://postgres:admin@localhost:5432/Drivers'),
    'dispatch':create_engine('postgres://postgres:admin@localhost:5432/dispatch')
}

i have two databases in sever and two tables.After that you can using Routing class to route for specific database connection while making a query :

  class RoutingSession(Session):
    def get_bind(self, mapper=None, clause=None):
        if mapper and issubclass(mapper.class_, drivers):
            return engines['drivers']
        elif self._flushing:
            return engines['dispatch']

now you can fire queries accordingly for eg first you need to make a session using like this :

Session = sessionmaker(class_=RoutingSession)
session = Session()
driverssql = session.query(drivers).all()

this was you can use multiple database in sqlalchemy

like image 28
divyanayan awasthi Avatar answered Oct 08 '22 11:10

divyanayan awasthi