Flask的sqlalchemy SQL練習

models.pymysql

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


# 數據庫配置信息
HOST = "127.0.0.1"
PORT = "3306"
DATABASE = "數據庫名字"
USERNAME = "用戶名"
PASSWORD = "密碼"


# 數據庫的固定格式
DB_URL = "mysql+pymysql://{username}:{password}@{host}:{port}/{db}?charset-utf8".format(
username=USERNAME,
password=PASSWORD,
host=HOST,
port=PORT,
db=DATABASE
)

# 建立一個引擎
engine = create_engine(DB_URL)

# 用declarative_base根據engine建立一個ORM基類
Base = declarative_base(engine)


# 建立一個ORM模型,這個模型繼承sqlalchemy給咱們提供基類,即上面的Base
class Depart(Base):
"""班級表"""
__tablename__ = "depart"
id = Column(Integer, primary_key=True, autoincrement=True)
caption = Column(String(64), nullable=False)

def __str__(self):
return self.caption

def __repr__(self):
return self.__str__()


class Student(Base):
"""學生表"""
__tablename__ = "student"
id = Column(Integer, primary_key=True, autoincrement=True)
name = Column(String(32), nullable=False)
gender = Column(Enum("", ""))
# 外鍵關聯
depart_id = Column(Integer, ForeignKey("depart.id"))
# 與生成表結構無關,僅用於查詢方便, backref指定反向查詢字段名(起一個關聯當前表的名字)
departs = relationship("Depart", backref="student_list")

def __str__(self):
return self.name

def __repr__(self):
return self.__str__()


class Teacher2Student(Base):
"""老師學生多對多關聯表"""
__tablename__ = "teacher2student"
id = Column(Integer, primary_key=True, autoincrement=True)
teacher_id = Column(Integer, ForeignKey("teacher.id"))
student_id = Column(Integer, ForeignKey("student.id"))


class Teacher2Depart(Base):
"""老師班級多對多關聯表"""
__tablename__ = "teacher2depart"
id = Column(Integer, primary_key=True, autoincrement=True)
teacher_id = Column(Integer, ForeignKey("teacher.id"))
depart_id = Column(Integer, ForeignKey("depart.id"))

__table_args__ = (
# 聯合惟一索引,加速查找、不重複
UniqueConstraint('teacher_id', 'depart_id', name='teacher_depart_id'),
# Index('st_id_name', 'name', 'extra'), # 聯合索引,加速查找
)


class Teacher(Base):
"""老師表"""
__tablename__ = "teacher"
id = Column(Integer, primary_key=True, autoincrement=True)
name = Column(String(64), nullable=False)
# secondary指定多對多中記錄的排序方式,前面的表明關聯類名字,後面是反向查詢本表的字段名
students = relationship("Student", secondary="teacher2student", backref="teacher_list")
departs = relationship("Depart", secondary="teacher2depart", backref="teacher_list")

def __str__(self):
return self.name

def __repr__(self):
return self.__str__()


class Course(Base):
"""課程表"""
__tablename__ = "course"
id = Column(Integer, primary_key=True, autoincrement=True)
title = Column(String(64), nullable=False)
teacher_id = Column(Integer, ForeignKey("teacher.id"))
scores = relationship("Score", backref="course_list")
teachers = relationship("Teacher", backref="course_list")

def __str__(self):
return self.title

def __repr__(self):
return self.__str__()


class Score(Base):
"""成績表"""
__tablename__ = "score"
id = Column(Integer, primary_key=True, autoincrement=True)
number = Column(Integer, nullable=False)
student_id = Column(Integer, ForeignKey("student.id"))
course_id = Column(Integer, ForeignKey("course.id"))
students = relationship("Student", backref="score_list")

def __str__(self):
return self.number

def __repr__(self):
return self.__str__()


# 將建立好的ORM模型,映射到數據庫中
Base.metadata.create_all()
# ORM對數據庫操做須要構建一個session對象
session = sessionmaker(engine)()
View Code

 

learn_sql.pysql

from learn.models import *
from learn.models import session


# 增(須要什麼字段添加什麼字段)
obj = Depart(caption="Go全棧")
session.add(obj)
session.commit()


session.add_all([Course(title="Go基礎"), Course(title="Java三大器")])
session.commit()


session.add_all([
Student(name="小五"),
Depart(caption="間諜"),
Teacher(name="海哥"),
Score(number=90),
Course(title="翻盤一號"),
])
session.commit()
# 建立一個新老師,並給他指定兩個新學生
obj = Teacher(name="二筒")
obj.students = [Student(name="小五", gender="", class_id=2), Student(name="二胖", gender="", class_id=3)]
session.add(obj)
session.commit()


# 查詢Python班級有多少學生
val = session.query(ClassTable.caption, Student.name).filter(ClassTable.id==1).all()
查詢課程id大於2的全部課程
val = session.query(Course).filter(Course.id > 2).all()
# 找到鋼蛋的老師
val = session.query(Student).filter(Student.name=="鋼蛋").first()
for item in val.teacher_list:
print(item)
# 查看小王老師教的課程
val = session.query(Teacher).filter(Teacher.name=="小王").first()
for item in val.courses:
print(item)

#
session.query(Teacher2Student).filter(Teacher2Student.id > 4).delete()
session.commit()
session.close()

# 修改學生屬性和關聯課程
session.query(Student).filter(Student.id == 8).update({Student.gender: ""})
session.query(Student).filter(Student.id == 9).update({Student.gender: ""})
session.query(Student).filter(Student.id == 10).update({Student.class_id: 2})
session.query(Student).filter(Student.id == 11).update({Student.class_id: 3})
session.commit()
View Code
相關文章
相關標籤/搜索