SQLAlchemy Layer - The Engine 说明

请添加图片描述

The Engine is the starting point for any SQLAlchemy application. It is “home base” for the actual database and its DBAPI, delivered to the SQLAlchemy application through a connection pool and a Dialect, which describes how to talk to specific kind of database/DBAPI combination.

The general structure can be illustrated as follows:
请添加图片描述

The Engine

  • 1 of 3 main layers for how you may choose to interact with the database
  • Is the lowest level layer of interacting with the database, and is much like using the DBAPI directly. Very similar to using psycopg2, managing a connection directly.
  • The Engine in SQLAlchemy refers to both itself, the Dialect and the Connection Pool, which all work together to interface with our database.
  • A connection pool gets automatically created when we create a SQLAlchemy engine.

The Engine is lowest layer of abstraction offered in SQLAlchemy for interacting with a database.


from sqlalchemy import create_engine

engine = create_engine('postgresql://localhost:5432/mydatabase')
conn = engine.connect()
result = conn.execute('SELECT * ...')

row = result.fetchone()
rows = result.fetchall()

result.close()

The above engine creates a Dialect object tailored towards PostgreSQL, as well as a Pool object which will establish a DBAPI connection at localhost:5432 when a connection request is first received. Note that the Engine and its underlying Pool do not establish the first actual DBAPI connection until the Engine.connect() method is called, or an operation which is dependent on this method such as Engine.execute() is invoked, In this way, Engine and Pool can be said to have a lazy initialization behavior.

The Engine, once created, can either be used directly to interact with the database, or can be passed to a Session object to work with the ORM. This section covers the details of configuration an Engine.


Guess you like

Origin blog.csdn.net/BSCHN123/article/details/121220103