How to Connect Flask to a MySQL Database: A Step-by-Step Tutorial

Flask is a popular Python web framework that makes it easy to build web applications quickly and efficiently. One common task when building a web application is to connect to a database to store and retrieve data. MySQL is a popular open-source relational database management system that is commonly used with Flask.

In this tutorial, we will cover how to connect Flask to a MySQL database using the Flask-MySQLdb extension. We will walk you through the process of installing the required packages, configuring your Flask application to connect to a MySQL database, creating a connection to the database, and displaying the data in an HTML template.

Step 1. Install the required packages: You’ll need the Flask and Flask-MySQLdb packages to connect to a MySQL database in Flask. You can install them using pip;

pip install Flask Flask-MySQLdb

Step 2. Import the required packages: In your Flask application file (usually app.py), import the required packages;

from flask import Flask, render_template, request
from flask_mysqldb import MySQL

Step 3. Set up the Flask app: Create a Flask app instance and configure it with your MySQL database details. Here’s an example;

app = Flask(__name__)

# MySQL configurations
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = 'password'
app.config['MYSQL_DB'] = 'mydatabase'

# Create a MySQL instance
mysql = MySQL(app)

Make sure to replace the values in the app.config dictionary with your own MySQL database details.

Step 4. Create a connection to the database: In your Flask app, create a connection to the MySQL database using the mysql.connection object;

@app.route('/')
def index():
    cur = mysql.connection.cursor()
    cur.execute('''SELECT * FROM mytable''')
    data = cur.fetchall()
    cur.close()
    return render_template('index.html', data=data)

In this example, we’re selecting all rows from a table called mytable and returning the data to an HTML template called index.html. Make sure to replace these with your own table and template names.

<!DOCTYPE html>
<html>
<head>
	<title>My App</title>
</head>
<body>
	<table>
		<thead>
			<tr>
				<th>ID</th>
				<th>Name</th>
				<th>Email</th>
			</tr>
		</thead>
		<tbody>
			{% for row in data %}
			<tr>
				<td>{{ row[0] }}</td>
				<td>{{ row[1] }}</td>
				<td>{{ row[2] }}</td>
			</tr>
			{% endfor %}
		</tbody>
	</table>
</body>
</html>

Step 5. Run the Flask app: Finally, run the Flask app using the app.run() method;

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

Conclusion

Connecting Flask to a MySQL database is a common task when building web applications. In this tutorial, we covered the steps needed to connect Flask to a MySQL database using the Flask-MySQLdb extension. We walked through installing the required packages, configuring your Flask application, creating a connection to the database, and displaying the data in an HTML template.

References
  • https://www.askpython.com/python-modules/flask/flask-mysql-database
  • https://hevodata.com/learn/flask-mysql/

Leave a Comment

Your email address will not be published. Required fields are marked *