Integrating MySQL with Flask for Database Access
In Flask web applications, accessing a MySQL database can enhance data management capabilities. To facilitate this integration, we provide comprehensive code examples to guide you through the process.
Step 1: Package Installation
Begin by installing the Flask-MySQL package, which enables MySQL connectivity. Use a command like:
pip install flask-mysql
Step 2: Configuration and Initialization
To establish a connection with MySQL, configure your application with the appropriate credentials:
<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>
Step 3: Database Operations
Once the connection is established, you can obtain connection and cursor objects to perform database operations:
<code class="python">conn = mysql.connect() cursor = conn.cursor() cursor.execute("SELECT * from User") data = cursor.fetchone()</code>
By following these code examples, you can seamlessly integrate MySQL into your Flask applications and effectively manage your data storage and retrieval needs.
The above is the detailed content of How to Integrate MySQL with Flask for Efficient Database Access?. For more information, please follow other related articles on the PHP Chinese website!