一.Flask的模型
安装Flask-SQLAlchemy
pip install sqlalchemy
(1)在models.py中定义:
db = SQLAlchemy()
(2)在manage.py中:
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:123456@127.0.0.1:3306/flask8'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.init_app(app)
二.Flask数据库的增删改查:
1.增
增加学生信息
db.session.add(stu)
sb.session.commit()
批量增加学生信息
db.session.add_all(stus)
db.session.commit()
2.删
db.session.delete(stu)
db.session.commit()
3.改
db.session.add(stu) : 更新内容可以不写
db.session.commit()
4.查
三种查询主键的方式:
Student.query.filter(Student.id == 1).first()
stu = Student.query.filter_by(id=1).first()
stu = Student.query.get(1)
查询第一个对象:
stu1 = Student.query.all()[0]
stu2 = Student.query.first()
(1)排序
order_by('-id') :表示安装id的降序排数据
order_by('id') :表示安装id的升序排数据
(2)分页
方法1(切片):
stus = Student.query.all()[:4]
方法2:
offset(m).limit(n):表示跳过m个参数,截取n个参数
(3)比较符号
gt ge lt le : 大于 大于等于 小于 小于等于
stus = Student.query.filter(Student.s_age.__gt__(30)).all()
第二种(直接使用> < >= <= ):
stus = Student.query.filter(Student.s_age > 30).all()
(4)模糊查询
包含查询:
stus = Student.query.filter(Student.s_name.contains('d')).all()
以什么开头:
stus = Student.query.filter(Student.s_name.startswith('p')).all()
以什么结尾:
stus = Student.query.filter(Student.s_name.endswith('e')).all()
模糊查询('_' 匹配一位,'%' 匹配任意长度的数据):
stus = Student.query.filter(Student.s_name.like('__a%')).all()
(5)多条件查询
且:
1.链式结构查询:
stus = Student.query.filter(Student.s_name.contains('e')).filter(Student.s_age > 35).all()
2._and方法或者,号隔开
stus = Student.query.filter(and_(Student.s_name.contains('e'), Student.s_age > 35)).all()
stus = Student.query.filter(Student.s_name.contains('e'), Student.s_age > 35).all()
或:
or_方法:
stus = Student.query.filter(or_(Student.s_name.contains('e'), Student.s_age > 35)).all()
非:
not_方法:
stus = Student.query.filter( not_(Student.s_name.contains('e') )).all()
(6)分页
第一种方法(切片):
第二种方法(limit offset):
第三种方法(paginate):
has_prev/has_next 是否有上一页/下一页
prev_num/next_num 上一页/下一页 的页码
page:当前页码 pages:总页数
循环取页码 iter_pages()