How to get Data from MySQL DB on Python Flask?

I´m learning Python Flask with MySQL Workbench, I have a database ‘books’ and a table ‘books.books_tb’ in my Workbench. I made a simple Flask app with the tutorial which looks like that:

from flask import Flask
from flask_mysqldb import MySQL

def home():
    def GetBookLink():
        mydb = mysql.connector.connect(
                    user = 'root',
                    database = 'books'
        mycursor = mydb.mycursor()

        mycursor.execute("SELECT * FROM books.books_tb") 
        DBData = mycursor.fetchall() 
        return DBData
    DBData = GetBookLink()
    return render_template("index.html", ScrapedBookData = DBData)

my index.html looks like that:

{% extends "base.html"%} {% block title %}Home{% endblock %}{% block content %}    
{% endblock %}

But I get an error (link at bottom) and as a newbie I don´t understand how to solve it. How can I solve this problem and write some queries to display the rows in my database?

[enter image description here][1]

>Solution :

From the first page of the documentation, you’re missing the instantiation of the MySQL class into a mysql variable.

from flask import Flask
from flask_mysqldb import MySQL

app = Flask(__name__)
mysql = MySQL(app)  # this is the instantiation

def users():
    cur = mysql.connection.cursor()
    cur.execute('''SELECT user, host FROM mysql.user''')
    rv = cur.fetchall()
    return str(rv)

if __name__ == '__main__':

Leave a Reply