Flask连接数据库

目录

 

导入相应包

创建接口

基于上述db对象创建一个Student

添加信息

显示学生信息

修改与删除信息


 

导入相应包

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

创建接口

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:123456@localhost:3306/studentinfo?charset=utf8'
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = True # 这一行如果不添加,程序会报警告。
db= SQLAlchemy(app)

基于上述db对象创建一个Student

class Student(db.Model):
     id     = db.Column(db.Integer, primary_key = True)
     name   = db.Column(db.String(100))
     sex = db.Column(db.String(100))
     studentId = db.Column(db.String(100))
     chinese = db.Column(db.String(200))
     math   = db.Column(db.String(100))
     english = db.Column(db.String(100))
     def __init__(self, name, sex, studentId, chinese, math, english): # __init__方法负责对象的初始化
         self.name = name
         self.sex = sex
         self.studentId = studentId
         self.chinese = chinese
         self.math = math
         self.english = english
​
db.create_all() # 将上述类映射到数据库中:
​

添加信息

html页面

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>学生信息</title>
</head>
<body>
    <h1>学生信息添加界面</h1>
     <form action = "{{ request.path }}" method = "post">
        <p><label for="name">姓名:</label><input type="text" name="name"></p>
        <p><label for="studentId">学号:</label><input type="text" name="studentId"></p>
        <p><label for="sex">性别</label><input type="radio" name="sex" value="男">男<input type="radio" name="sex" value="女">女</p>
        <p><label for="chinese">语文</label><input type="number" name="chinese"></p>
        <p><label for="math">数学</label><input type="number" name="math"></p>
        <p><label for="english">英语</label><input type="number" name="english"></p>
        <input type="submit" name="" value="添加">
    </form>
</body>
</html>

将表单的action直接指向当前路径,这就要求在当前路径所对应的函数中,对POST数据进行处理:

@app.route('/newstudent/', methods = ['GET', 'POST'])
def newstudent():
    if request.method == 'POST':
        if request.form['name'] and request.form['studentId'] and request.form['sex'] and request.form['chinese'] and request.form['math'] and request.form['english']:
            curuser = Student(request.form['name'], request.form['studentId'], request.form['sex'], request.form['chinese'], request.form['math'], request.form['english'])
            db.session.add(curuser)
            db.session.commit()
            return redirect(url_for('AllStudent'))
    return render_template('info.html')
​

显示学生信息

html页面

<!DOCTYPE html>
<html>
<head>
     <meta charset="UTF-8">
    <title>学生信息列表</title>
</head>
<body>
    <h1>学生信息列表</h1>
     <h3>新建 (<a href = "{{ url_for('newstudent') }}">增加学生</a>)</h3>
    <table border="1">
        <thead>
          <tr>
            <th>姓名</th>
            <th>学号</th>
            <th>性别</th>
            <th>语文</th>
            <th>数学</th>
            <th>英语</th>
​
          </tr>
        </thead>
        <tbody>
         {% for student in students %}
          <tr>
            <td>{{ student.name }}</td>
            <td>{{ student.studentId }} </td>
            <td> {{ student.sex }} </td>
            <td>{{ student.chinese }} </td>
            <td> {{ student.math }} </td>
            <td>{{ student.english }} </td>
          </tr>
         {% endfor %}
​
        </tbody>
    </table>
</body>
</html>

添加路由

@app.route('/allstudent/')
def AllStudent():
   return render_template('allinfo.html', students = Student.query.all() )

修改与删除信息

html页面如下

<!DOCTYPE html>
<html>
<head>
     <meta charset="UTF-8">
    <title>学生信息列表</title>
</head>
<body>
    <h1>学生信息列表</h1>
     <h3>新建 (<a href = "{{ url_for('newstudent') }}">增加学生</a>)</h3>
    <table border="1">
        <thead>
          <tr>
            <th>姓名</th>
            <th>学号</th>
            <th>性别</th>
            <th>语文</th>
            <th>数学</th>
            <th>英语</th>
              <th>操作</th>
​
          </tr>
        </thead>
        <tbody>
         {% for student in students %}
          <tr>
            <td>{{ student.name }}</td>
            <td>{{ student.studentId }} </td>
            <td> {{ student.sex }} </td>
            <td>{{ student.chinese }} </td>
            <td> {{ student.math }} </td>
            <td>{{ student.english }} </td>
              <td><a href = "{{ url_for('modifystudent', studentid=student.id) }}">修改</a>&nbsp;&nbsp;<a href = "{{ url_for('deletestudent', studentid=student.id) }}">删除</a></td>
​
          </tr>
         {% endfor %}
​
        </tbody>
    </table>
</body>
</html>

修改代码如下

@app.route('/modifystudent/<studentid>/', methods = ['GET', 'POST'])
def modifystudent(studentid):
     curuser = db.session.query(Student).filter_by(id=studentid).one()
     if request.method == 'POST':
         if request.form['studentId'] and request.form['sex'] and request.form['chinese'] and  request.form['math'] and request.form['english']:
             curuser.studentId   = request.form['studentId']
             curuser.sex = request.form['sex']
             curuser.chinese = request.form['chinese']
             curuser.math = request.form['math']
             curuser.english = request.form['english']
             db.session.commit()
             return redirect(url_for('AllStudent'))
     return render_template('modifyinfo.html', curuser=curuser)

删除代码如下

@app.route('/deleteuser/<studentid>/')
def deletestudent(studentid):
     db.session.query(Student).filter_by(id=studentid).delete()
     db.session.commit()
     return redirect(url_for('AllStudent'))

 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

几两春秋梦_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值