数据库链接的步骤
一、导入pymysql包
import pymysql
二、获取链接
conn = pymysql.connect(host='localhost', port=3306,user='root',passwd='root',db='flask',charset='UTF8')
三、获取游标
cursor = conn.cursor()
四、执行execute()
cursor.execute(sql)
五、提交
conn.commit()
六、关闭链接
代码
#coding=utf8
from flask import Flask,request,render_template
import pymysql
app = Flask(__name__)
@app.route('/',methods=['POST','GET'])
def regist():
if request.method=='POST':
username = request.form.get('username')
password = request.form.get('passwd')
conn = pymysql.connect(host='localhost', port=3306,user='root',passwd='root',db='flask',charset='UTF8')
cursor = conn.cursor()#获取一个游标
print('1-----')
sql = "INSERT INTO FLASK.USER(USERNAME,PASSWD) VALUES("+username+","+password+")"
print(sql)
cursor.execute(sql)
#数据提交
conn.commit()
cursor.close()
conn.close()
return 'Welcome %s ,your passwd is %s' %(username,password)
else:
return render_template('regist.html')
if __name__ == '__main__':
app.run()
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">
username:<input type="text" name="username"><br>
password:<input type="password" name="passwd"><br>
headimg: <input type="file" name="headimg"><br>
<input type="submit" value="OK">
</form>
</body>
</html>