> For the complete documentation index, see [llms.txt](https://huang-jason.gitbook.io/python/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://huang-jason.gitbook.io/python/sqlalchemy.md).

# SQLAlchemy

<https://auth0.com/blog/sqlalchemy-orm-tutorial-for-python-developers/>

## 1. Engines: db connection

Engines = manage **Pools** and **Dialects**.

```python
engine = create_engine('postgresql://usr:pass@localhost:5432/sqlalchemy')
```

creating an engine does ***not*** connect to the database instantly

### Pool = to improve performance.

1. Opening and maintaining new connections is expensive
2. Easier management of # of connections simultaneously.

### Dialects = adopt to different DB.

## 2. Session vs Connection

session = exec ORM sql query

connection = exec RAW sql query

## 3. Sessions: sync orm & db

1. modifications ORM tracked & applied to DB.
2. guarantee the database consistency.

```python
# create a configured "Session" class
Session = sessionmaker(bind=engine)

# create a Session
session = Session()
```

## 4. Base: base class for all models

```python
Base = declarative_base()
```
