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