IN THIS TUTORIAL WE’RE GOING TO LEARN PYTHON FLASK MYSQL CONECTION, WE’RE GOING TO LEARN HOW TO CONNECT FLASK TO MYSQL DATABASE AND YOU CAN INSERT THE FORM DATA.
This tutorial is completely made for beginner, So the prerequisite of this tutorial is going to be minimum only thing which I will personally recommend it to have a high level overview of Python web services using Flask and have minimum understanding of SQL and Database set up.
To get started you’ll be needing any IDE I’ll be using PyCharm,MySQL DB and that’s it!!! This tutorial, unlike my earlier posts will be steps depicting what and how to do….
- Open PyCharm, create new Python file name app.python and type the below code into your app.python file.
from flask import Flask app = Flask(__name__) @app.route('/', methods=['GET', 'POST']) def index(): return "Hello Nuclear Geeks" if __name__ == '__main__': app.run()
- If you’ve gone through Python web services using Flask you would understand 100% of the above code. Simply we’re routing out request and displaying “Hello Nuclear Geeks”, On running the following program type http://127.0.0.1:5000/ on your browser to see the output!! “Hello Nuclear Geeks”
- Now you need to create a simple HTML page with two text field First Name, Last Name and submit button. To do this create a folder named Templates inside it create a file index.html and copy the below code.
<HTML> <BODY bgcolor="cyan"> <form method="POST" action=""> <center> <H1>Enter your details </H1> <br> First Name <input type = "text" name= "fname" /> <br> Last Name <input type = "text" name = "lname" /> <br> <input type = "submit"> </center> </form> </BODY> </HTML>
- Modify our app.python file and add the below code in it.
from flask import Flask, render_template app = Flask(__name__) @app.route('/', methods=['GET', 'POST']) def index(): return render_template('index.html') if __name__ == '__main__': app.run()
- Upon running the above code you must get the page as below.
- Now we’ve developed our form, the next step is database connection. To create a table use the below query:
CREATE TABLE MyUsers ( firstname VARCHAR(30) NOT NULL, lastname VARCHAR(30) NOT NULL);
- The above query will create a table in the Database with name MyUsers, now copy the following code and paste in app.python file.
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'] = 'root' app.config['MYSQL_DB'] = 'MyDB' mysql = MySQL(app) @app.route('/', methods=['GET', 'POST']) def index(): if request.method == "POST": details = request.form firstName = details['fname'] lastName = details['lname'] cur = mysql.connection.cursor() cur.execute("INSERT INTO MyUsers(firstName, lastName) VALUES (%s, %s)", (firstName, lastName)) mysql.connection.commit() cur.close() return 'success' return render_template('index.html') if __name__ == '__main__': app.run()
- Pretty easy till now!!!
app.config[‘MYSQL_HOST’] = ‘localhost’
app.config[‘MYSQL_USER’] = ‘root’
app.config[‘MYSQL_PASSWORD’] = ‘root’
app.config[‘MYSQL_DB’] = ‘MyDB’
These lines represent the db configuration required for our Flask, the next line ‘mysql = MySQL(app)’ creates an instance which will provide us the access.
The lines ‘firstName = details[‘fname’]’ and ‘lastName = details[‘lname’]’ fetches the entered value in the HTML form.
Establishment of connection is done by ‘cur = mysql.connection.cursor()’ and execution of query by ‘cur.execute(“INSERT INTO MyUsers(firstName, lastName) VALUES (%s, %s)”, (firstName, lastName))’
Once the execution is done you can commit and close the connection
- Heavy Breathing!!! we are all set to run…. Run the program enter the First Name = “Aditya” and Last Name= “Malviya” and tap on submit. You will see success being returned on the screen.
- Open the database and run the following query..
SELECT * FROM MyUsers;
- You will be seeing the following output…..
> mysql> select * from MyUsers; +-----------+----------+ | firstname | lastname | +-----------+----------+ | Aditya | Malviya | +-----------+----------+
1 row in set (0.00 sec)
Easy !!! This was all about MySQL connection using Flask. In the next tutorial we will be playing with multiple request and multiple tables….
Do Comment if you have any queries, I’ll be more than happy to help you.