How to use MySQLdb connection data in python
This article mainly introduces how to use MySQLdb connection data in python, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let Xiaobian take you to understand.
1. File structure
The use of MySQLdb and pymysql is similar to that of reading friends who can try to achieve it on their own.
two。 Experimental effect
3. Master file: main.pyimport MySQLdbfrom flask_wtf import FlaskFormfrom wtforms.validators import DataRequired,EqualTo,Lengthfrom wtforms import StringField,SubmitField,PasswordField,TelFieldfrom flask import Flask,render_template,redirect,url_for,abort,request,jsonifyapp=Flask (_ _ name__) app.secret_key='stu'# connection data mysqlconn=MySQLdb.connect (host='127.0.0.1', port=3306, user='root', password='root') Db='main') cur=conn.cursor () # add user form class StuForm (FlaskForm): name=StringField (label=' user name:', validators= [DataRequired ()]) password=PasswordField (label=' password:', validators= [DataRequired (), Length (min=3,max=8)]) submit=SubmitField (label=' submission') # search user form class SStuForm (FlaskForm): name=StringField (label=' user name:' Validators= [DataRequired ()]) submit=SubmitField (label=' submission') # Update user form class UStuForm (FlaskForm): name = StringField (label=' user name:', validators= [DataRequired ()]) password = PasswordField (label=' password:', validators= [DataRequired (), Length (min=3, max=8)]) submit=SubmitField (label=' submission') # Delete user form class DStuForm (FlaskForm): name = StringField (label=' user name:' Validators= [DataRequired ()]) submit = SubmitField (label=' submission') def CreateTab (): sql= "create table student (name varchar (20), password varchar (30)" cur.execute (sql) conn.commit () cur.close () @ app.route ('/ add',methods= ['POST') 'GET']) def add (): 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 () return jsonify ('Add sucessings') Return render_template ('add.html',stuform=stuform) @ app.route (' / search',methods= ['POST') 'GET']) def search (): sstuform=SStuForm () if request.method=='POST': if sstuform.validate_on_submit (): name=sstuform.name.data sql=f "select count (name) from student where name=' {name}'" cur.execute (sql) conn.commit () count=cur.fetchone () [0] if count