Home > Mobile >  How to get Data from MySQL DB on Python Flask?
How to get Data from MySQL DB on Python Flask?

Time:06-14

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

@app.route('/books')
def home():
    def GetBookLink():
        mydb = mysql.connector.connect(
                    host='localhost',
                    user = 'root',
                    database = 'books'
                    )
        mycursor = mydb.mycursor()

        
        
        mycursor.execute("SELECT * FROM books.books_tb") 
        DBData = mycursor.fetchall() 
        mycursor.close()
        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 %}    
<h1>{{ScrapedBookData}}</h1>
{% 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] [1]: https://i.stack.imgur.com/lZTGQ.png

CodePudding user response:

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


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

if __name__ == '__main__':
    app.run(debug=True)
  • Related