Working With SQLAlchemy
Learn how to start using SQL databases in Python.
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.
Press + to interact
from sqlalchemy import create_engine, Column, typesfrom sqlalchemy.ext.declarative import declarative_basefrom sqlalchemy.orm import sessionmakerconnection_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)
...