Connecting to sqlite3 database from Flask application and printing data on a webpage

Issue

I’m using sqlite3 database, conda environment and python Flask to create a simple web app that displays the users from a db table.

from flask import Flask, render_template
import sqlite3

app = Flask(__name__)

@app.route("/")
def index():
    db = sqlite3.connect("data.db", check_same_thread=False)
    rows = db.execute("SELECT * FROM users").fetchall()
    db.commit()
    return render_template("index.html", rows=rows)

index.html:

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Users</title>
    </head>
    <body>
        <h1>Users</h1>
        <ul>
            {% for row in rows %}
                <li>{{row["name"]}}, {{row["email"]}}</li>
            {% endfor %}
        </ul>
    </body>
</html>

There’s no error but when running the app on localhost no list is displayed on the page. There’s only the heading and the bullet point. So I guess db.execute is returning an empty object.

Can anyone please tell me what’s going wrong? Thanks!

Solution

You have to open cursor before fetch result

def index():
    db = sqlite3.connect("data.db")
    cursor = db.cursor()
    rows = cursor.execute("SELECT * FROM users").fetchall()
    cursor.close()
    return render_template("index.html", rows=rows)

p.s. rows is not dictionary it is tuple, use zip to convert to dict:
if you have just two colums in users
rows=[dict(zip(('name', 'email'), row)) for row in rows]

Answered By – Rostyslav

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published