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


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__)

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


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

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!


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()
    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