Categories
Python Answers

How to use MySQL in Python Flask?

Spread the love

Sometimes, we want to use MySQL in Python Flask.

In this article, we’ll look at how to use MySQL in Python Flask.

How to use MySQL in Python Flask?

To use MySQL in Python Flask, we use the flask-mysql package.

To install it, we run

pip install flask-mysql

Then in our app’s entry point file, we add

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)

to set the MySQL creadentials in the config.

We call mysql.init_app with app to incorporate flask-mysql into our Flask app.

Then we can use

conn = mysql.connect()
cursor = conn.cursor()

cursor.execute("SELECT * from User")
data = cursor.fetchone()

to connect to our database with mysql.connect.

And we get the cursor with conn.cursor.

Then we make our query with

cursor.execute("SELECT * from User")
data = cursor.fetchone()

Conclusion

To use MySQL in Python Flask, we use the flask-mysql package.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *