ORM and SQLAlchemy — The ‘Magic Wand’ in Database Management

Abstract database interactions with ORM

Source: photo by bqthanh on kipalog.com
cursor = db.cursor()
sql = 'INSERT INTO Person(name, age) VALUES ("Alice", 21)'
cursor.execute(sql)
db.commit()
Source: fullstackpython.com
from django.db import modelsclass Person(models.Model):
first_name = models.CharField()
last_name = models.CharField()
phone_number = models.CharField()
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String
Base = declarative_base()class Person(Base):
__tablename__ = 'Person'

id = Column(Integer, primary_key=True)
first_name = Column(String)
last_name = Column(String)
address = Column(String)
from sqlalchemy import create_engine
engine = create_engine('sqlite:///:memory:')
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String
Base = declarative_base()class Employee(Base):
__tablename__ = 'employees'
id = Column(Integer, primary_key=True)
name = Column(String)
age = Column(Integer)
from sqlalchemy.orm import sessionmakerSession = sessionmaker()
Session.configure(bind=engine)
session = Session()
res = session.query(Employee).filter_by(name='Alice').all()
res = session.query(Employee).filter_by(name='Alice')
.order_by(Employee.id)
.limit(5)
.all()
bob = Employee(name='Bob', age=21)
session.add(bob)
session.commit()
bob = session.query(Employee).filter_by(name='Bob').first() 
bob.age = 22
session.commit()
mistake = Employee(name='mistake', age=0)
session.add(mistake)
session.rollback()
$ alembic upgrade head

--

--

CS Student, Software Engineer, Writer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store