Search⌘ K
AI Features

Working With SQLAlchemy

Understand how to use SQLAlchemy to set up and manage databases in Python for full stack development. Learn to create classes representing database tables, define columns with types, and configure connection strings to link with your database. This lesson helps you build foundational skills to organize and access data effectively within your web applications.

Managing database with SQLAlchemy

First, install SQLAlchemy using pipenv install sqlalchemy.

Let’s say we want to track our favorite books. We know each book by its title and author, and also want to track whether it’s available to lend to a friend. First, we create a class that represents the table. Each instance of the class, that is, each object, will be an individual book.

Python 3.5
from sqlalchemy import create_engine, Column, types
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
connection_string = "sqlite:///database.db"
db = create_engine(connection_string)
base = declarative_base()
class Book(base):
__tablename__ = 'books'
id = Column(types.Integer, primary_key=True)
author = Column(types.String(length=50))
title = Column(types.String(length=120), nullable=False)
available = Column(types.Boolean, nullable=False)
...