Search⌘ K
AI Features

How to Create a Database

Explore how to create a database in Python using the SQLAlchemy declarative approach. Learn to define table classes, establish primary and foreign keys, and use relationships to manage many-to-one connections. Understand how the database engine connects and communicates with SQLite, and how to run code that builds your database tables effectively.

We'll cover the following...

Creating a database with SQLAlchemy is really easy. SQLAlchemy uses a Declarative method for creating databases. We will write some code to generate the database and then explain how the code works. If you want a way to view your SQLite database, I would recommend the SQLite Manager plugin for Firefox. Here’s some code to create our database tables:

Python
# table_def.py
from sqlalchemy import create_engine, ForeignKey
from sqlalchemy import Column, Date, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, backref
engine = create_engine('sqlite:///mymusic.db', echo=True)
Base = declarative_base()
class Artist(Base):
""""""
__tablename__ = "artists"
id = Column(Integer, primary_key=True)
name = Column(String)
class Album(Base):
""""""
__tablename__ = "albums"
id = Column(Integer, primary_key=True)
title = Column(String)
release_date = Column(Date)
publisher = Column(String)
media_type = Column(String)
artist_id = Column(Integer, ForeignKey("artists.id"))
artist = relationship("Artist", backref=backref("albums", order_by=id))
# create tables
Base.metadata.create_all(engine)

If you run this code, then you should see ...