How to Create a Database
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.pyfrom sqlalchemy import create_engine, ForeignKeyfrom sqlalchemy import Column, Date, Integer, Stringfrom sqlalchemy.ext.declarative import declarative_basefrom sqlalchemy.orm import relationship, backrefengine = 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 tablesBase.metadata.create_all(engine)
If you run this code, then you should see ...