Home >Database >Mysql Tutorial >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
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>
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>
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>
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!