Search code examples
pythonmysqlflaskflask-mysql

Trying to use Flask-mysql with python


I'm trying to get Flask to connect to a local MySQL but this keeps failing. I have tried multiple combinations based on other forums

from flask.ext.mysql import MySQL
from flask_mysql import MySQL
from flaskext.mysql import MySQL

etc.

the error I get is the following

ImportError: No module named flask.ext.mysql

Running Windows 10 & Python3.5 I have pip installed flask-MySQL

********** EDIT ***********

With the help of the user @metmirr (Thank you!!!) the fix was to use a virtual environment, couldn't get it to work any other way! The answer and comments have been removed somehow


Solution

  • Use mysql.connector for accessing MySQL from Flask. For more details visit the link.

    Import MySQL Connector

    import mysql.connector
    

    Connect to local database

    def getMysqlConnection():
        return mysql.connector.connect(host='localhost',database='test',user='root',password='root')
    

    To access the database

    db = getMysqlConnection()
    sqlstr = "select * from test_table"
    cur = db.cursor()
    cur.execute(sqlstr)
    output_json = cur.fetchall()