python3.7.4+mysql環(huán)境下,簡單的用戶管理
#app.py
from flask import Flask,render_template,request
from pymysql import connect
app = Flask(__name__)
@app.route('/')
def home():
return render_template('home.html')
@app.route('/addPerson')
def addPerson():
return render_template('addPerson.html')
@app.route('/commit',methods = ['POST','GET'])
def commit():
if request.method == 'POST':
print('進入post')
try:
name = request.form['studentName']
city = request.form['city']
address = request.form['address']
phone = request.form['phone']
con = connect('localhost', 'root', '123456', 'test1')
cur = con.cursor()
#經(jīng)過多次實驗粤剧,這個語句才最適合現(xiàn)在的python+mysql
sql = "INSERT INTO myfirst(name,city,address,phonenumber) VALUES ('{}','{}','{}','{}')".format(name,city,address,phone)
print(sql)
cur.execute(sql)
con.commit()
msg = "添加成功"
except Exception as e:
con.roolback()
msg = "添加失敗"
print(msg)
finally:
con.close()
print(msg)
return render_template('result.html',message = msg)
@app.route('/lookup')
def lookup():
con = connect('localhost', 'root', '123456', 'test1')
cur = con.cursor()
cur.execute("select * from myfirst")
rows = cur.fetchall()
con.close()
return render_template("list.html", rows=rows)
if __name__ == '__main__':
app.run(debug = True)
<!-- addPerson.html -->
<!DOCTYPE html>
<html>
<head>
<title>addPerson</title>
</head>
<body>
<form action="/commit" method="POST">
<h3>填寫學生信息</h3>
<br>
name<br>
<input type="text" name="studentName">
<br>
address<br>
<textarea name="address"></textarea>
<br>
city<br>
<input type="text" name="city">
<br>
phone<br>
<input type="text" name="phone">
<br>
<input type="submit" value="submit">
</form>
</body>
</html>
<!-- home.html -->
<!DOCTYPE html>
<html>
<head>
<title>home</title>
</head>
<body>
<div>
<a href="/addPerson">新增用戶</a>
</div>
<div>
<a href="/lookup">查詢用戶</a>
</div>
</body>
</html>
<!-- list.html -->
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h1>學生信息表</h1>
<table border = 1>
{%for row in rows%}
<tr>
<td>{{row[0]}}</td>
<td>{{row[1]}}</td>
<td>{{row[2]}}</td>
<td>{{row[3]}}</td>
<td>{{row[4]}}</td>
</tr>
{%endfor%}
</table>
<a href = "/">Go back to home page</a>
</body>
</html>
<!-- result.html -->
<!DOCTYPE html>
<html>
<head>
<title>添加結(jié)果</title>
</head>
<body>
<h1>添加結(jié)果是:{{message}}</h1>
<br>
<a href="/">返回主頁</a>
</body>
</html>