flask-数据库之增删改查
2019-01-23 本文已影响0人
憧憬001
一、增删改
# 添加:
db.session.add(stu)
db.session.commit()
# 例:
@blue.route('/add_stu/', methods=['GET'])
def add_stu():
if request.method == 'GET':
# 插入数据
stu = Student()
stu.s_name = '火云邪神'
db.session.add(stu)
db.session.commit()
return '创建学生信息成功'
# 删除操作
db.session.delete(stu)
db.session.commit()
# 修改:
db.session.add(stu) # add()方法写不写都行
db.session.commit()
# 如果觉得代码量过多可以封装一下
from datetime import datetime
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class Student(db.Model):
__tablename__ = 'student'
# Integer = INTEGER = INT
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
s_name = db.Column(db.String(10),unique=True,nullable=False)
s_age = db.Column(db.Integer, default=20)
s_gender = db.Column(db.Boolean, default=1)
create_time = db.Column(db.DateTime, default=datetime.now)
# 封装一个添加的方法
def save(self):
db.session.add(self)
db.session.commit()
# 封装一个删除的方法
def delete(self):
db.session.delete(self)
db.session.commit()
# 封装一个更新的方法
def update(self):
db.session.commit()
二、查
- filter()方法
filter(模型名.字段==值)
或 filter_by(字段=值)
-
all()方法
查询所有数据,结果为列表 -
first()方法
查询filter或filter_b结果中的第一个对象 -
get()方法
获取主键所在行的对象信息
get()方法能获取对象,则返回,获取不到对象则为空
# filter()方法
# 查询方式一
stu = Student.query.filter(Student.s_name=='东方不败')
# 方式二
stu = Student.query.filter_by(s_name='东方不败')
# 获取第一个对象
stu = Student.query.all()[0]
print(stu)
stu = Student.query.first()
print(stu)
stu = Student.query.get(1)
print(stu)
- 排序
id : 升序
-id:降序
stus = Student.query.order_by('-id').all()
stus = Student.query.order_by('id').all()
- 分页
offset():跳过多少个
limit():查看多少个
stus = Student.query.all()[:4]
stus = Student.query.offset(1).limit(3).all()
- 范围查询
gt:>
ge:>=
lt:<
le:<=
# 方式一
stus = Student.query.filter(Student.s_age.__gt__(20)).all()
# 方式二(这里支持 简写的比较运算符)
stus = Student.query.filter(Student.s_age >= 20).all()
- 模糊查询
contains() :包含某个内容
startwith():以...开始
endwith(): 以...结束
like() :
_:占位
%:任何内容
stus = Student.query.filter(Student.s_name.contains('不')).all()
stus = Student.query.filter(Student.s_name.startswith('张')).all()
stus = Student.query.filter(Student.s_name.endswith('蓉')).all()
stus = Student.query.filter(Student.s_name.like('__冲%')).all()