[PYTHON] sqlalchemy tutorial

sqlalchemy: ORM (Object Relational Mapper) made by python. ORM is, in a nutshell, a library that can treat Relational DataBase like a Python Object.

Installation

$ pip install SQLAlchemy

1. Create a database

1. Connect to the database

from sqlalchemy import create_engine
engine = create_engine('sqlite:///:memory:', echo=True)

If echo = True, the issued SQL will be spit out in the log

2. Create a base class

from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()

3. Define the table

from sqlalchemy import Column, Integer, String

class User(Base):
    __tablename__ = 'users'

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

    def __repr__(self):
        return "<User(name='%s', fullname='%s', password='%s')>" % (
                self.name, self.fullname, self.password)

4. Make a table

Base.metadata.create_all(engine)

To summarize the above

database_setup.py


from sqlalchemy import Column, ForeignKey, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy import create_engine

Base = declarative_base()


class Restaurant(Base):
    __tablename__ = 'restaurant'

    id = Column(Integer, primary_key=True)
    name = Column(String(250), nullable=False)

    @property
    def serialize(self):
        """Return object data in easily serializeable format"""
        return {
            'name': self.name,
            'id': self.id,
        }


class MenuItem(Base):
    __tablename__ = 'menu_item'

    name = Column(String(80), nullable=False)
    id = Column(Integer, primary_key=True)
    description = Column(String(250))
    price = Column(String(8))
    course = Column(String(250))
    restaurant_id = Column(Integer, ForeignKey('restaurant.id'))
    restaurant = relationship(Restaurant)

    @property
    def serialize(self):
        """Return object data in easily serializeable format"""
        return {
            'name': self.name,
            'description': self.description,
            'id': self.id,
            'price': self.price,
            'course': self.course,
        }


engine = create_engine('sqlite:///restaurantmenu.db')


Base.metadata.create_all(engine)

2. Add members to the table

1. Calling an object in database_setup.py

from sqlalchemy import create_engine
from database_setup import Base, Restaurant, MenuItem
engine = create_engine('sqlite:///restaurantMenu.db')
Base.metadata.bind=engine

2. Create a session

from sqlalchemy.orm import sessionmaker
Session = sessionmaker(bind=engine)
session = Session()

3. CRUD operation

#create
new_restaurant = Restaurant(name='Pizza Palace')
session.add(new_restaurant)
session.commit()

#read
session.query(Restaurant).all()

#update
burger = session.query(MenuItem).filter_by(name = 'Burger').one()
burger.price = '$2.99'
session.add(burger)
session.commit()

#delete
ice_cream = session.query(MenuItem).filter_by(name = 'Ice Cream').one()
session.delete(ice_cream)
session.commit()

See Official Tutorial for details. It's very well organized.

Recommended Posts

sqlalchemy tutorial
sqlalchemy
SQLAlchemy notes
PyODE Tutorial 2
Python tutorial
PyODE Tutorial 1
PyODE Tutorial 3
SQLAlchemy Pit
SQLAlchemy BaseModel
TensorFlow tutorial tutorial
Quantopian Tutorial LESSON 10
RabbitMQ Tutorial 5 (Topic)
Quantopian Tutorial LESSON 8
Quantopian Tutorial LESSON 1, 2
Quantopian Tutorial LESSON 6
Python Django Tutorial (5)
Python Django Tutorial (2)
Python tutorial summary
RabbitMQ Tutorial 6 (RPC)
django tutorial memo
Ryu tutorial Addendum
Python Django Tutorial (8)
Python Django Tutorial (6)
Start Django Tutorial 1
Quantopian Tutorial LESSON 9
Quantopian Tutorial LESSON 5
[SQLAlchemy] Read data
Quantopian Tutorial LESSON 3
Quantopian Tutorial LESSON 7
5 minute gRPC tutorial
Python Django Tutorial (7)
Python Django Tutorial (1)
Quantopian Tutorial LESSON 4
Python Django tutorial tutorial
Quantopian Tutorial LESSON 11
Python Django Tutorial (3)
RabbitMQ Tutorial 4 (Routing)
zipline Beginner Tutorial
[Translation] hyperopt tutorial
Python Django Tutorial (4)