flask项目中,创建mysql数据表格,并实现增、删、查、改
需要两个安装包:
pip install pymysql
pip install flask-sqlalchemy
1. __init__py
# 配置访问mysql数据库
app.config['SQLALCHEMY_DATABASE_URI']= 'mysql+pymysql://root:123123@localhost:3306/flask3'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# 访问mysql数据库 初始化app
SQLAlchemy(app=app)
2. models.py
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class Student(db.Model):
# 要自己定义id
s_id = db.Column(db.Integer, primary_key=True,autoincrement=True)
s_name = db.Column(db.String(20), unique=True)
s_age = db.Column(db.Integer, default=18)
# 定义表格的名字
__tablename__ = 'student'
3. views.py
# 创建表格
@stu.route('/createtable/')
def create_db():
db.create_all()
return '创建成功'
# 删除表格
@stu.route('/droptable/')
def drop_db():
db.drop_all()
return '删除成功'
# 给表格中添加内容, 刷新一次页面创建一行记录
@stu.route('/createstu/')
def create_stu():
stu = Student()
stu.s_name = '小帅%d' % random.randrange(1000)
stu.s_age = '%d' % random.randrange(20)
# 向表格中添加数据
db.session.add(stu)
try:
# 提交表格模型到数据库
db.session.commit()
except:
db.session.rollback()
return '创建学生成功'
# 获取所有学生
@stu.route('/stulist/')
def stu_all():
stus = Student.query.all()
return render_template('stulist.html',stus=stus)
# 获取学生信息详情
@stu.route('/studetails/')
def stu_detail():
# 使用原生SQL
# sql = 'select * from student;'
# sql = 'select * from student where s_name="小帅420";'
# stus = db.session.execute(sql)
# 使用filter
stus = Student.query.filter(Student.s_name=='小帅420')
# 使用filter_by
stus = Student.query.filter_by(s_name='小帅587')
return render_template('stulist.html',stus=stus)
# 改
@stu.route('/updatestu/')
def update_stu():
# 第一种方式
stu = Student.query.filter_by(s_id=3).first()
stu.s_name = '李二狗'
# 第二种方式
# Student.query.filter(Student.s_id==5).update({'s_name':'李二狗'})
db.session.commit()
return redirect(url_for('stu.stu_all'))
# 删
@stu.route('/deletestu/')
def delete_stu():
stu = Student.query.filter(Student.s_id==4).first()
db.session.delete(stu)
db.session.commit()
return redirect(url_for('stu.stu_all'))