flask操作MySQL
利用flask,pymsql,实现网页对MySQL进行增加和查看数据的功能
app.py
from flask import Flask, render_template, request
import pymysql
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")
# 1.连接MySQL
conn = pymysql.connect(host="127.0.0.1", port=3306, user='root', passwd="123456", charset='utf8', db='unicom')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
# 2.提交SQL语句
sql = "insert into admin(username,password,mobile) values(%s,%s,%s)"
cursor.execute(sql, [username, password, mobile])
conn.commit()
# 3.关闭SQL连接
cursor.close()
conn.close()
return "success"
@app.route("/show/user")
def show_user():
######获取所有信息#######
# 1.连接MySQL
conn = pymysql.connect(host="127.0.0.1", port=3306, user='root', passwd="123456", charset='utf8', db='unicom')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
# 2.提交SQL语句
sql = "select * from admin"
cursor.execute(sql)
data_list = cursor.fetchall()
# 3.关闭SQL连接
cursor.close()
conn.close()
print(data_list)
return render_template("show_user.html", data_list=data_list)
if __name__ == '__main__':
app.run()
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>
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-dist/css/bootstrap.css">
</head>
<body>
<div class="container">
<h1>用户列表</h1>
<table border="1" 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-dist/js/bootstrap.js"></script>
</body>
</html>