Sqlalchemy Engine
What is an Engine?
Then Engine is the starting point of any sqlalchemy application.
Above engine references both Dialect and a Pool.
Dialect and Pool together interpret the DBAPI’s module functions
as well as the behavior of the database.
Creating an Engine?
Create_engine() function is used
Create_engine(“postgresql://scott:tiger@localhost:5432/
mydatabase”)
The above engine creates a Dialect objet towards PostgreSQL, as
well as the pool object which will establish a DBAPI connection at
localhost:5432 when a connection request is first received.
Pool and Engine has lazy initialization behavior.
The Engine, once created can either be used directly to interact
with the database, or can be passed to Session object to work
with the ORM.
Dialects
- The create_engine function produces an Engine object based on a
URL.
- Include username, password, hostname, database optional
KWARGS, some cases a file path is accepted/
Dialects URLS
- Dialect+driver://username:password@host:port/database
- Dialect == sqlite, mysql, postgresql, oracle or mssql
- Drivername is the DBAPI to be used to connect to the database
- If some special character is present in the connection url that it
need to be encoded using urllib.parse.quote_plus()
Engine Creation API’s
1) Create_engine(url, **kwargs)
o Creating a new engine instance.
o Kwargs instruct underlying dialect and pool constructs
o Establish connection using the underlying Pool once using
the engine.connect() or Engine.execute() is invoked.
o Create engine() call itself doesn’t establish any actual DBAPI
connections directly.
2) Create_mock_engine(url, executor, **kw)
o Create a mock engine echoing for DDL statement.
o Storing and debugging the output of DDL sequences
generated by MetaData.create_all() and related methods.
o
SQLAlchemy Events
- From sqlalchemy import event
- @event.listens_for(engine, “do_connect”)
- Def fun(dialect, conn_rec, cargs, c_params)
- @event.listens_for(engine, “connect”)
- Def con(dbapi_connection, conn_record)