flask连接数据库并在页面展示数据

python代码如下

from flask import Flask, render_template, request
import pymysql

app = Flask(__name__)

@app.route("/add/user", methods=["GET", "POST"])
def addUser():
    if request.method == "GET":
        return render_template("add.html")
    conn = pymysql.connect(user="root", password="123456", host="192.168.91.100", charset="utf8", port=3306, db="test")
    curses = conn.cursor()
    name = request.form.get("name")
    phone = request.form.get("phone")
    rmk = request.form.get("rmk")
    sql = 'insert into user(name, phone, remarks) values(%s, %s, %s)'
    curses.execute(sql, [name, phone, rmk])
    conn.commit()
    conn.close()
    return "add success"

@app.route("/show/user")
def showUser():
    conn = pymysql.connect(user="root", password="123456", host="192.168.91.100", charset="utf8", port=3306, db="test")
    #返回字典形式查询结果
    curses = conn.cursor(cursor=pymysql.cursors.DictCursor)
    sql = "select * from user"
    #执行sql语句
    curses.execute(sql)
    #获取所有的查询结果
    data = curses.fetchall()
    return render_template("info.html", data=data)

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

页面代码如下
add.html

<form action="/add/user" method="post">
    <input type="text" placeholder="姓名" name="name">
    <input type="text" placeholder="电话" name="phone">
    <input type="text" placeholder="备注" name="rmk">
    <input type="submit" value="提交">
</form>

info.html

<table border="1">
    <thead>
        <tr>
            <th>name</th>
            <th>phone</th>
            <th>备注</th>
        </tr>
    </thead>
    <tbody>
    {% for item in data %}
        <tr>
            <td>{{ item.name }}</td>
            <td>{{ item.phone }}</td>
            <td>{{ item.remarks }}</td>
        </tr>
    {% endfor %}
    </tbody>
</table>

image

posted @   whtjyt  阅读(1424)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示