Flask数据库的增删改查

数据库的增删改查

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
import random

from flask import Blueprint, render_template, request, url_for, redirect

from app.models import Student, db
from sqlalchemy import and_, not_, or_

blue = Blueprint('app', __name__)


@blue.route('/')
def hello():
return 'hello'


@blue.route('/list/', methods=['GET'])
def stu_list():
# students = Student.query.all()
# 分页
# pre_page:一页多少条
page = int(request.args.get('page', 1))
pre_page = 5
paginate = Student.query.paginate(page, pre_page)
# paginate.items 获取当前页面的内容
students = paginate.items
return render_template('list.html', paginate=paginate, students=students)


@blue.route('/add/', methods=['GET', 'POST'])
def stu_add():
if request.method == 'GET':
return render_template('add.html')
if request.method == 'POST':
# 创建学生信息
# 1.获取数据
username = request.form.get('username')
phone = request.form.get('phone')
age = request.form.get('age')
# 2.保存
stu = Student()
stu.s_name = username
stu.s_phone = phone
stu.s_age = age
db.session.add(stu)
db.session.commit()
return redirect(url_for('app.stu_list'))


@blue.route('/edit/<int:id>/', methods=['GET', 'POST'])
def stu_edit(id):
if request.method == 'GET':
# stu = Student.query.filter(Student.id == id).first()
stu = Student.query.filter_by(id=id).first()
return render_template('add.html', stu=stu)

if request.method == 'POST':
# 1.获取页面的参数
username = request.form.get('username')
phone = request.form.get('phone')
age = request.form.get('age')
# 2.获取对象
# stu = Student.query.filter(Student.id == id).first()
stu = Student.query.filter_by(id=id).first()
# 3.修改属性
stu.s_name = username
stu.s_phone = phone
stu.s_age = age
db.session.add(stu)
db.session.commit()
return redirect(url_for('app.stu_list'))


@blue.route('/del/<int:id>/', methods=['GET'])
def stu_del(id):
if request.method == 'GET':
# 获取删除对象
# stu = Student.query.filter(Student.id == id).first()
stu = Student.query.filter_by(id=id).first()
# 使用delete(对象)
db.session.delete(stu)
db.session.commit()
return redirect(url_for('app.stu_list'))


@blue.route('/add_all/', methods=['GET'])
# 批量创建
def add_all():
stus = []
for i in range(10):
stu = Student()
stu.s_age = random.randint(18,28)
stu.s_name = '小明%s' % random.randint(0,10000)
stu.s_phone = '12345678911'
stus.append(stu)
# db.session.add(stu)
db.session.add_all(stus)
db.session.commit()
return '创建成功'


@blue.route('/change_stu/', methods=['GET'])
# 修改时db.session.add(对象)可以不用写
def change_stu():
stu = Student.query.filter(Student.id == 8).first()
stu.s_name = '小花'
# db.session.add(stu)
db.session.commit()
return '修改成功'


@blue.route('sel_stu', methods=['GET'])
def sel_stu():
# 查询id为6的信息
# first(): 获取第一个
stu = Student.query.filter(Student.id == 3).first()
stu = Student.query.filter_by(id=3).first()
# get(主键):只能获取主键那一行的信息
stu = Student.query.get(5)
# 查询所有数据
# all()返回所有数据的列表结果
stus = Student.query.all()
# 排序:升序
stus = Student.query.order_by('s_age')
stus = Student.query.order_by('s_age asc')
# 排序:降序
stus = Student.query.order_by('-s_age')
stus = Student.query.order_by('s_age desc')
# 实现分页 offset(跳过几个参数) limit(截取几条数据):
stu = Student.query.offset(0).limit(2)

# 模糊查询contains
stus = Student.query.filter(Student.s_name.contains('小花')).all()
# 以小开头的学生信息 startswith
stus = Student.query.filter(Student.s_name.startswith('小')).all()
# 以3结尾的学生信息
stus = Student.query.filter(Student.s_name.endswith('3')).all()

# 第二位为‘明’ 的学生信息, like '_明%'
stus = Student.query.filter(Student.s_name.like('_明%')).all()

# 查询id为1,2,3,4,5,的学生信息 in_([1,2,3,4,5])
stus = Student.query.filter(Student.id.in_([1, 2, 3, 4, 5]))
# 查询年龄小于21的信息
# 小于/小于等于 lt le 大于/大于等于 gt/ge
stus = Student.query.filter(Student.s_age.__le__(21)).all()
stus = Student.query.filter(Student.s_age <= 21).all()

# 查询年龄小于22且姓名以6结束
stus = Student.query.filter(Student.s_age<22).filter(Student.s_name.endswith('6')).all()
stus = Student.query.filter(Student.s_age<22, Student.s_name.endswith('6')).all()
# and_
stus = Student.query.filter(and_(Student.s_age < 22, Student.s_name.endswith('6'))).all()
# or_
stus = Student.query.filter(or_(Student.s_age < 22, Student.s_name.endswith('6'))).all()
# not_
stus = Student.query.filter(not_(Student.s_age < 22)).all()
# 分页
stus = Student.query.paginate(1, 5)

names = [stu.s_name for stu in stus]
print(names)

return '查询成功'

###models

1
2
3
4
5
6
7
8
9
10
11
12
13

from flask_sqlalchemy import SQLAlchemy


db = SQLAlchemy()


class Student(db.Model):
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
s_name = db.Column(db.String(80), unique=True, nullable=False)
s_phone = db.Column(db.String(11), nullable=True)
s_age = db.Column(db.Integer, nullable=False)
s_gender = db.Column(db.Integer, default=1)

###配置数据库

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

from flask import Flask
from flask_script import Manager

from app.models import db
from app.views import blue

app = Flask(__name__)

app.register_blueprint(blueprint=blue, url_prefix='/app/')

# 配置数据库
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:123456@127.0.0.1:3306/flask7'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db.init_app(app)


manage = Manager(app)
if __name__ == '__main__':
manage.run()