Accessing MySQL in Flask Applications
When it comes to connecting to a MySQL database from a Python Flask application, there are no shortage of resources available online. However, these resources often overlook MySQL, instead focusing solely on SQLite.
This article will provide a comprehensive guide on how to establish a MySQL connection from within a Flask application. By following the steps outlined below, you can easily connect to your MySQL database and begin executing queries.
Preparatory Steps
Before diving into the code, you need to ensure that Flask-MySQL, a package that provides MySQL support for Flask, is installed. If you don't already have it, you can install it using pip:
pip install flask-mysql
Configuration and Initialization
Once Flask-MySQL is installed, you can add the necessary configuration and initialize MySQL:
from flask import Flask from flaskext.mysql import MySQL app = Flask(__name__) # Set MySQL configuration app.config['MYSQL_DATABASE_USER'] = 'root' app.config['MYSQL_DATABASE_PASSWORD'] = 'root' app.config['MYSQL_DATABASE_DB'] = 'EmpData' app.config['MYSQL_DATABASE_HOST'] = 'localhost' # Initialize MySQL mysql = MySQL() mysql.init_app(app)
Establishing a Connection and Executing Queries
With the configuration in place, you can now establish a connection and cursor to execute raw queries against your MySQL database:
# Obtain a connection object conn = mysql.connect() # Get a cursor cursor =conn.cursor() # Execute a select query cursor.execute("SELECT * from User") # Fetch the first row data = cursor.fetchone()
By following the instructions in this article, you can seamlessly connect to MySQL databases and perform your desired queries from within your Flask application.
The above is the detailed content of How to Connect to a MySQL Database from a Flask Application?. For more information, please follow other related articles on the PHP Chinese website!