前端+python+MYSQL案例
安装插件
pip3 install flask
pip install cryptography
pip3 install pymysql
文件位置
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/c77ad8db4b9f970f386a62daebb8c84e.png)
新增用户
from flask import Flask,render_template, request
import pymysql
app = Flask(__name__)
@app.route('/add/user', methods=["GET","POST"])
def add():
if request.method == "GET":
return render_template("add_user.html")
username = request.form.get("user")
pwd = request.form.get("pwd")
mobile = request.form.get("mobile")
conn = pymysql.connect(host="127.0.0.1", port=3306, user="root", password="root", charset='utf8', db='bkys')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
sql = "insert into admin(username,password,mobile) values(%s,%s,%s)"
cursor.execute(sql, [username, pwd, mobile])
conn.commit()
cursor.close()
conn.close()
return "添加成功"
if __name__ == '__main__':
app.run()
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<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>
查询所有用户
from flask import Flask,render_template, request
import pymysql
app = Flask(__name__)
@app.route('/add/user', methods=["GET","POST"])
def add():
if request.method == "GET":
return render_template("add_user.html")
username = request.form.get("user")
pwd = request.form.get("pwd")
mobile = request.form.get("mobile")
conn = pymysql.connect(host="127.0.0.1", port=3306, user="root", password="root", charset='utf8', db='bkys')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
sql = "insert into admin(username,password,mobile) values(%s,%s,%s)"
cursor.execute(sql, [username, pwd, mobile])
conn.commit()
cursor.close()
conn.close()
return "添加成功"
@app.route("/show/user")
def show_user():
conn = pymysql.connect(host="127.0.0.1", port=3306, user="root", password="root", charset='utf8', db='bkys')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
sql = "select * from admin"
cursor.execute(sql)
data_list = cursor.fetchall()
cursor.close()
conn.close()
print(data_list)
return render_template("show_user.html",data_list=data_list)
if __name__ == '__main__':
app.run()
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用户列表</title>
</head>
<body>
<h1>用户列表</h1>
<table border="1">
<thead>
<tr>id</tr>
<tr>name</tr>
<tr>user</tr>
<tr>mobile</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>
</body>
</html>