Home > Database > Mysql Tutorial > body text

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

Mary-Kate Olsen
Release: 2024-10-28 06:19:02
Original
856 people have browsed it

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
Copy after login

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)
Copy after login

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()
Copy after login

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

The above is the detailed content of How to Connect to a MySQL Database from a Flask Application?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!