In this tutorial, we will guide you through how to install and use MySQL with the Flask framework easily.
The first requirement is to have Python and Flask installed at your system, as we assume that you already do, let's dive directly to installing flask-mysql package.
If not, follow this tutorial:
Install flask-mysql package
pip install flask-mysql
Import flask-mysql
In your flask app file, let's import the flask-mysql package:
Now, we can connect to the MySQL database using the following, do not forget to replace the connection data with your own.
Retrieve and display data from MySQL using Flask
Now we can start using the database, let's say that you have a list of users in the users table, in the following snippet, we will reterive all users and render their information in users.html.
The following is the users.html template, which will render the data from get_users function.
Create and Insert Records into database
Here is how to use Flask to insert a new record into the users table, using an HTML form.
@app.route('/insert', methods=['POST'])
def insert_data():
name = request.form['name']
age = request.form['age']
cursor = mysql.connection.cursor()
query = f"INSERT INTO users (name, age) VALUES ('{name}', {age})"
cursor.execute(query)
mysql.connection.commit()
cursor.close()
return 'Data inserted successfully!'
Delete records from a MySQL database with Flask
@app.route('/delete/<int:id>')
def delete_data(id):
cursor = mysql.connection.cursor()
query = f"DELETE FROM table_name WHERE id = {id}"
cursor.execute(query)
mysql.connection.commit()
cursor.close()
return 'Data deleted successfully!'