Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (50.2k points)
I want to know more about Flask, kindly share some codes on how to access a MySQL DB? There have been records showing how to connect to SQLite but not on MySQL.

1 Answer

0 votes
by (108k points)
edited by

For achieving your goal, you need to work with a package named Flask-MySQL package. First, install the module with the pip command:

pip install flask-mysql

After that, you need to combine some configuration and initialize MySQL:

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)

Now you can do the connection and cursor objects and can able to execute raw queries:

conn = mysql.connect()

cursor =conn.cursor()

cursor.execute("SELECT * from User")

data = cursor.fetchone()

If you are newbie and want to explore more about Python, then learn python from the below video tutorial:

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Dec 1, 2020 in Python by laddulakshana (16.4k points)
0 votes
1 answer
asked Jul 27, 2019 in SQL by Soni Kumari (40.7k points)

Browse Categories

...