@rollin
To get data from a MySQL database in a Python Flask application, follow these steps:
- Install the necessary packages:
Install the MySQL Connector package: pip install mysql-connector-python
- Import the required libraries and create a connection to the MySQL database:
from flask import Flask
import mysql.connector
app = Flask(__name__)
# Create a connection to the MySQL database
mydb = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="your_database"
)
- Create a Flask route to retrieve data from the database:
@app.route('/data', methods=['GET'])
def get_data():
# Create a cursor to execute SQL queries
cursor = mydb.cursor()
# Execute the query to retrieve data from the database
cursor.execute("SELECT * FROM your_table")
# Fetch all the rows returned by the query
data = cursor.fetchall()
# Convert the data to a JSON response
response = []
for row in data:
response.append(row) # Modify this based on your needs
# Close the cursor and the database connection
cursor.close()
return jsonify(response)
- Run the Flask application:
if __name__ == '__main__':
app.run()
Now, when you visit the /data
route in your Flask application, it will return JSON data retrieved from the MySQL database. Adjust the code according to your specific needs, such as modifying the SQL query or transforming the result data.