本篇主要记录常用的 CURD
操作。
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class User(db.Model):
# 下面是定义表内字段
index = db.Column('index', db.Integer, primary_key=True, autoincrement=True)
nick = db.Column(db.String(100), default="unknown")
email = db.Column(db.String(255), unique=True)
phone = db.Column(db.String(11), unique=True)
# 这里是赋值操作,一个User类实例化后,对应的就是一条记录
def __init__(self, index, nick, email, phone):
self.index = index
self.nick = nick
self.email = email
self.phone = phone
" ------ 增(Create) ------ "
@classmethod
def create_one_user(cls): # 单条增加
user = cls(nick="lionlone", email="xxxx")
db.session.add(user)
db.session.commit()
@classmethod
def create_users(cls): # 批量增加
user1 = cls(nick="lionlone1", email="xxx1")
user2 = cls(nick="lionlone2", email="xxx2")
db.session.add_all([user1,user2])
db.session.commit()
" ------ 查(Read) ------ "
@classmethod
def select_user(cls):
cls.query.all() # 获取所有记录
cls.query.all() # 获取所有记录
cls.query.first() # 获取第一条记录
cls.query.filter(cls.nick == 'lionlone1').first() # 获取指定条件的第一条值
# 对查询结果过滤:跳过符合条件的第一条记录,从第2条开始,往后最多返回2条数据
cls.query.filter(cls.nick == 'lionlone1').offset(1).limit(2).all()
# 键值处于某个范围区间内
cls.query.filter(cls.nick.between("lionlone")).all()
# 键值包含某字符串
cls.query.filter(cls.nick.contains("lionlone")).all()
# 键值不包含某字符串
cls.query.filter(not_(cls.nick.contains("lionlone"))).all()
# 键值被包含于某个列表中
cls.query.filter(cls.nick.in_(["lionlone1","lionlone2"])).all()
# 键值不被包含于某个列表中
cls.query.filter(cls.nick.notin_(["lionlone1","lionlone2"])).all()
# 键值以某个字符开始
cls.query.filter(cls.nick.startswith("a")).all()
# 键值以某个字符结束
cls.query.filter(cls.nick.endswith("a")).all()acs
# 模糊查询
cls.query.filter(User.nick.like("%n%g")).all()
# 逻辑表达式 AND OR NOT
from sqlalchemy import not_, or_, and_
cls.query.filter(and_(cls.nick.startswith("a"),cls.nick.endswith("b"))).all()
cls.query.filter(or_(cls.nick.startswith("a"),cls.nick.endswith("b"))).all()
cls.query.filter(not_(cls.nick.startswith("a")).all()
# 排序,默认根据主键升序,desc()降序,asc()升序
cls.query.order_by(cls.index.desc()).all()
" ------ 改(Update) ------ "
@classmethod
def update_one_user(): # 先查后改
db.session.query(cls).filter(cls.nick == "lionlone").update({"phone":"xxxxx"})
" ------ 删(Delete) ------ "
@classmethod
def delete_user(): # 先查后删,无论查询结果是单条还是多条。
db.session.query(cls).filter(cls.nick == 'lionlone').delete()