app.py
import pymysql
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/add/user', methods=["GET", "POST"])
def add_user():
if request.method == "GET":
return render_template('add_user.html') # 修正模板文件名
username = request.form.get("user")
password = request.form.get("pwd")
mobile = request.form.get("mobile")
# 连接MySQL
conn = pymysql.connect(host="localhost", port=3306, user='root', passwd="root", charset='utf8', db='unicom')
cursor = conn.cursor(pymysql.cursors.DictCursor)
# 发送指令
sql = "insert into admin(username,password,mobile) values(%s,%s,%s)"
cursor.execute(sql, (username, password, mobile))
conn.commit()
# 关闭
cursor.close()
conn.close()
return "添加成功"
@app.route("/show/user")
def show_user():
# 从数据库获取所有用户信息
conn = pymysql.connect(host="localhost", port=3306, user='root', passwd="root", charset='utf8', db='unicom')
cursor = conn.cursor(pymysql.cursors.DictCursor)
sql = "select * from admin"
cursor.execute(sql)
data_list = cursor.fetchall()
cursor.close()
conn.close()
return render_template('show_user.html', data_list=data_list) # 修正变量名
if __name__ == '__main__':
app.run(debug=True) # 可以开启debug模式以便调试
show_user.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="/static/plugins/bootstrap-3.4.1/css/bootstrap.css">
</head>
<body>
<div class="container">
<h1>用户列表</h1>
<table class="table table-bordered">
<thead>
<tr>
<th>ID</th>
<th>姓名</th>
<th>密码</th>
<th>手机号</th>
</tr>
</thead>
<tbody>
{% for item in data_list %}
<tr>
<td>{{ item.id }}</td>
<td>{{ item.username }}</td>
<td>{{ item.password }}</td>
<td>{{ item.mobile }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<script src="/static/js/jquery-3.6.0.min.js"></script>
<script src="/static/plugins/bootstrap-3.4.1/js/bootstrap.js"></script>
</body>
</html>
add_user.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>添加数据</h1>
<form method="post" action="/add/user">
<input type="text" name="user" placeholder=" 用户名 ">
<input type="text" name="pwd" placeholder=" 密码">
<input type="text" name="mobile" placeholder=" 手机号 ">
<input type="submit" value="提交">
</form>
</body>
</html>