Flask+MySQL
from flask import Flask, render_template, request
import pymysql
app = Flask(__name__)
@app.route('/add/user', methods=['POST', 'GET'])
def add_user():
if request.method == 'GET':
return render_template('add_user.html')
else:
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='1234', charset='utf8', db='shizhounian')
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.关闭连接
cursor.close()
conn.close()
return '添加成功'
@app.route('/show/user')
def show_user():
######## 从数据库获取信息 #########
# 1.连接MySQL
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='1234', charset='utf8', db='shizhounian')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
# 2.执行SQL
sql = 'select * from admin'
cursor.execute(sql)
data_list=cursor.fetchall()
# 3.关闭连接
cursor.close()
conn.close()
print(data_list)
return render_template('show_user.html',data_list=data_list)
if __name__ == '__main__':
app.run(debug='true')
插入数据
<!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="password" name="pwd" placeholder="密码">
<input type="text" name="mobile" placeholder="手机号">
<input type="submit" value="submit">
</form>
</body>
</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">
<link rel="stylesheet" href="/static/plugins/font-awesome-4.7.0/css/font-awesome.css">
<link rel="stylesheet" href="/static/plugins/bootstrap-datetimepicker/css/bootstrap-datetimepicker.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.7.0.min.js.js"></script>
<script src="/static/plugins/bootstrap-3.4.1/js/bootstrap.js"></script>
</body>
</html>