"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Connect to a MySQL Database from a Flask Application?

How to Connect to a MySQL Database from a Flask Application?

Published on 2024-11-20
Browse:223

How to Connect to a MySQL Database from a Flask Application?

Accessing MySQL in Flask Applications

When it comes to connecting to a MySQL database from a Python Flask application, there are no shortage of resources available online. However, these resources often overlook MySQL, instead focusing solely on SQLite.

This article will provide a comprehensive guide on how to establish a MySQL connection from within a Flask application. By following the steps outlined below, you can easily connect to your MySQL database and begin executing queries.

Preparatory Steps

Before diving into the code, you need to ensure that Flask-MySQL, a package that provides MySQL support for Flask, is installed. If you don't already have it, you can install it using pip:

pip install flask-mysql

Configuration and Initialization

Once Flask-MySQL is installed, you can add the necessary configuration and initialize MySQL:

from flask import Flask
from flaskext.mysql import MySQL

app = Flask(__name__)

# Set MySQL configuration
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = 'root'
app.config['MYSQL_DATABASE_DB'] = 'EmpData'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'

# Initialize MySQL
mysql = MySQL()
mysql.init_app(app)

Establishing a Connection and Executing Queries

With the configuration in place, you can now establish a connection and cursor to execute raw queries against your MySQL database:

# Obtain a connection object
conn = mysql.connect()

# Get a cursor
cursor =conn.cursor()

# Execute a select query
cursor.execute("SELECT * from User")

# Fetch the first row
data = cursor.fetchone()

By following the instructions in this article, you can seamlessly connect to MySQL databases and perform your desired queries from within your Flask application.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3