PyMysql is python library,used to connect with mysql database.

You can get PyMysql using the below link.

https://github.com/PyMySQL/PyMySQL


pip install PyMySQL

Execute the above command to install PyMysql.

PyMysql is to be a drop-in replacement for MySQLdb and work on CPython, PyPy and IronPython.

We are going to save username and email in database. Create a table in mysql with username and email column.


create table userdata
(id int(2) primary key auto_increment,
username text,
email text)

Create a connection to database using PyMysql.


import pymysql.cursors

# Connect to the database
connection = pymysql.connect(host='localhost',
                             user='user',
                             password='passwd',
                             db='db',
                             charset='utf8mb4',
                             cursorclass=pymysql.cursors.DictCursor)

Create a registration form with username and email as inpput field.

flask-get-reg

 

Catch form values and save them in database using insert query and close the connection.


@app.route('/save-post',methods=['POST', 'GET'])
def signUp():
    if request.method=='POST':
     name=request.form['name']
     email=request.form['email']
     try:
      with connection.cursor() as cursor:
      # Read a single record
      sql = "INSERT INTO userdata (username,email) VALUES (%s, %s)"
      cursor.execute(sql, (name,email))
      connection.commit()
     finally:
      connection.close()
      return "Saved successfully."
    else:
      return "error"

Here post method is used to pass data.Thats all. You saved data in database.  

 

Full code


from flask import Flask, render_template,request,json
import pymysql.cursors

# Connect to the database
connection = pymysql.connect(host='localhost',
                             user='user',
                             password='passwd',
                             db='db',
                             charset='utf8mb4',
                             cursorclass=pymysql.cursors.DictCursor)
app = Flask(__name__)




@app.route("/get-reg")
def login():
    return render_template('reg.html')

@app.route('/save-post',methods=['POST', 'GET'])
def signUp():
    if request.method=='POST':
     name=request.form['name']
     email=request.form['email']
     try:
  

      with connection.cursor() as cursor:
      # Read a single record
        sql = "INSERT INTO userdata (username,email) VALUES (%s, %s)"
        cursor.execute(sql, (name,email))
        connection.commit()
     finally:
      connection.close()
      return "Saved successfully."
    else:
      return "error"
       


if __name__ == "__main__":
    app.run()