简体   繁体   中英

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

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

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)

ps 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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM