1.文件结构:
2.实验效果:
3.关于MySQLdb的下载可以参考以下博主:
(1)https://blog.csdn.net/wanglei19891210/article/details/105785063/
(2)https://blog.csdn.net/cn_1937/article/details/81533544
4.主文件main.py:
import MySQLdb
from flask_wtf import FlaskForm
from wtforms.validators import DataRequired,EqualTo,Length
from wtforms import StringField,SubmitField,PasswordField,TelField
from flask import Flask,render_template,redirect,url_for,abort,request,jsonify
app=Flask(__name__)
app.secret_key='stu'
#连接数据mysql
conn=MySQLdb.connect(
host='127.0.0.1',
port=3306,
user='root',
password='root',
db='main'
)
cur=conn.cursor()
class StuForm(FlaskForm):
name=StringField(label='用户名: ',validators=[DataRequired()])
password=PasswordField(label='密码: ',validators=[DataRequired(),Length(min=3,max=8)])
submit=SubmitField(label='提交')
def CreateTab():
sql="create table student(name varchar(20),password varchar(30))"
cur.execute(sql)
conn.commit()
cur.close()
@app.route('/index',methods=['POST','GET'])
def index():
stuform=StuForm()
if request.method=='POST':
if stuform.validate_on_submit():
name=stuform.name.data
password=stuform.password.data
print('name: {}'.format(name))
print('password: {}'.format(password))
sql=f"insert into student(name,password) values('{name}','{password}')"
cur.execute(sql)
conn.commit()
cur.close()
return jsonify('Add Successed!')
return render_template('insert.html',stuform=stuform)
if __name__ == '__main__':
print('Pycharm')
# CreateTab()
app.run(debug=True)
5.前端文件insert.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Insert</title>
<style>
div{
width:255px;
height:100px;
margin:auto;
margin-top:200px;
border:2px solid #000000;
font-size:20px;
font-weight:400px;
background:#FFFFFF;
}
.submit{
margin-top:10px;
margin-left:100px;
}
</style>
</head>
<body>
<div>
<form action="" method="POST">
{{stuform.csrf_token()}}
{{stuform.name.label}}{{stuform.name}}<br>
{{stuform.password.label}}{{stuform.password}}<br>
<input class="submit" type="submit" name="submit" value="添加">
</form>
</div>
</body>
</html>