Home > Database > Mysql Tutorial > body text

How to Integrate MySQL with Flask for Data Persistence?

Mary-Kate Olsen
Release: 2024-10-26 05:01:02
Original
751 people have browsed it

How to Integrate MySQL with Flask for Data Persistence?

Integrating MySQL with Flask: A Practical Guide

Connecting to a MySQL database in Flask can be an essential task for web applications that require data persistence. While the Flask documentation provides instructions for working with SQLite, this article addresses the steps involved in accessing MySQL.

Step 1: Install Flask-MySQL Package

To get started, install the Flask-MySQL package, which acts as a bridge between Flask and MySQL:

pip install flask-mysql
Copy after login

Step 2: Configure and Initialize MySQL

In your Python script, add the necessary configuration and initialize MySQL:

<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

Here, we specify the username, password, database name, and host for MySQL.

Step 3: Get Connection and Cursor Objects

Next, obtain connection and cursor objects to interact with the database:

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

Step 4: Execute Queries

With the connection and cursor established, you can execute raw MySQL queries:

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

This example query retrieves the first row of the "User" table and assigns it to the "data" variable.

Conclusion

By following these steps, you can seamlessly integrate MySQL into your Flask application. The Flask-MySQL package facilitates database operations, allowing you to store and retrieve data with ease.

The above is the detailed content of How to Integrate MySQL with Flask for Data Persistence?. 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!