Before starting, Hope you are aware basics of Flask if not Please visit Flask Web Development Tutorial. Now Here I am putting the following steps that we use to connect Flask to MySql:-
from flask import Flask,render_template, request
from flask_mysqldb import MySQL
app = Flask(__name__)
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = ''
app.config['MYSQL_DB'] = 'flask'
mysql = MySQL(app)
Above code is used to create the initial connection with MySQL.
Now the next step is to configure the MySQL Connection Cursor. We use Cursor to establish a connection with MySQL, it interacts with database tables. It can scan the database for data, execute SQL queries, and delete table records.
Below is the code that we use for configuring MySQL Connection cursor
mysql = MySQL(app)
#Creating a connection cursor
cursor = mysql.connection.cursor()
#Executing SQL Statements
cursor.execute(''' CREATE TABLE table_name(field1, field2...) ''')
cursor.execute(''' INSERT INTO table_name VALUES(v1,v2...) ''')
cursor.execute(''' DELETE FROM table_name WHERE condition ''')
#Saving the Actions performed on the DB
mysql.connection.commit()
#Closing the cursor
cursor.close()
Now we will create a small Flask application that use to store form data in MySQL DB, with name as app.py
from flask import Flask,render_template, request
from flask_mysqldb import MySQL
app = Flask(__name__)
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = ''
app.config['MYSQL_DB'] = 'flask'
mysql = MySQL(app)
@app.route('/form')
def form():
return render_template('form.html')
@app.route('/login', methods = ['POST', 'GET'])
def login():
if request.method == 'GET':
return "Login via the login Form"
if request.method == 'POST':
name = request.form['name']
age = request.form['age']
cursor = mysql.connection.cursor()
cursor.execute(''' INSERT INTO info_table VALUES(%s,%s)''',(name,age))
mysql.connection.commit()
cursor.close()
return f"Done!!"
app.run(host='localhost', port=5000)
Now when the user submits the data, it will get submitted and saved directly to the MySQL DB
Now create form.html by using the below code.
<form action="/login" method = "POST">
<p>name <input type = "text" name = "name" /></p>
<p>age <input type = "integer" name = "age" /></p>
<p><input type = "submit" value = "Submit" /></p>
</form>
Start the server by running the file using the python app.py command.
Now when you go to localhost:5000/form and enter the information and submit the form, you will see that your information is stored in the database table.
Check out more tutorial in Flask here – How to upload file in Flask?