How to get data from mysql on python flask?

Member

by rollin , in category: MySQL , 7 months ago

How to get data from mysql on python flask?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by elise_daugherty , 7 months ago

@rollin 

To get data from a MySQL database in a Python Flask application, follow these steps:

  1. Install the necessary packages: Install the MySQL Connector package: pip install mysql-connector-python
  2. 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" )
  3. 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)
  4. 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.