1 min read

Python SQLAlchemy

SQLAlchemy is the Python SQL toolkit and Object Relational Mapper (ORM) that gives application developers the full power and flexibility of SQL.

Installation

pip install SQLAlchemy

Connecting to a Database

To connect to a database, we use create_engine():

from sqlalchemy import create_engine

# SQLite database
engine = create_engine('sqlite:///example.db', echo=True)

Declarative Mapping

SQLAlchemy uses a system known as Declarative to define classes that map to database tables.

from sqlalchemy.orm import declarative_base
from sqlalchemy import Column, Integer, String

Base = declarative_base()

class User(Base):
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True)
    name = Column(String)
    fullname = Column(String)
    nickname = Column(String)

    def __repr__(self):
       return f"<User(name='{self.name}', fullname='{self.fullname}', nickname='{self.nickname}')>"

Creating the Schema

Base.metadata.create_all(engine)

Creating a Session

The Session is the handle to the database.

from sqlalchemy.orm import sessionmaker

Session = sessionmaker(bind=engine)
session = Session()

CRUD Operations

Create

ed_user = User(name='ed', fullname='Ed Jones', nickname='edsnickname')
session.add(ed_user)
session.commit()

Read

our_user = session.query(User).filter_by(name='ed').first()
print(our_user)

Update

ed_user.nickname = 'eddie'
session.commit()

Delete

session.delete(ed_user)
session.commit()

programming/python/python