Home  >  Article  >  Database  >  How to Connect Flask Applications to a MySQL Database?

How to Connect Flask Applications to a MySQL Database?

Susan Sarandon
Susan SarandonOriginal
2024-10-26 06:01:30421browse

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

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>

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>

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>

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!

Statement:
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