Home > Database > Mysql Tutorial > body text

How to Connect Flask Applications to a MySQL Database?

Susan Sarandon
Release: 2024-10-26 06:01:30
Original
420 people have browsed it

How to Connect Flask Applications to a MySQL Database?

Connecting Flask to MySQL

In Flask, connecting to MySQL requires an additional extension known as Flask-MySQL. Here's a step-by-step guide to achieve this:

1. Install Flask-MySQL

Start by installing the Flask-MySQL package using pip:

pip install flask-mysql
Copy after login

2. Configure MySQL Settings

In your Flask application, add the following to configure and initialize a MySQL object:

<code class="python">from flask import Flask
from flaskext.mysql import MySQL

app = Flask(__name__)
mysql = MySQL()
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = 'root'
app.config['MYSQL_DATABASE_DB'] = 'EmpData'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)</code>
Copy after login

3. Connect to MySQL

Now, you can access MySQL by retrieving the connection and cursor objects:

<code class="python">conn = mysql.connect()
cursor =conn.cursor()</code>
Copy after login

4. Execute Queries

With the connection and cursor in place, you can perform raw queries. For instance:

<code class="python">cursor.execute("SELECT * from User")
data = cursor.fetchone()</code>
Copy after login

This retrieves the first row of data from the 'User' table. Remember to close the cursor and connection objects when you're done.

The above is the detailed content of How to Connect Flask Applications to a MySQL Database?. 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!