Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

@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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[enter image description here][1]
[1]: https://i.stack.imgur.com/lZTGQ.png

>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


@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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading