【问题标题】:Connecting to sqlite3 database from Flask application and printing data on a webpage从 Flask 应用程序连接到 sqlite3 数据库并在网页上打印数据
【发布时间】:2021-05-23 02:50:57
【问题描述】:

我正在使用 sqlite3 数据库、conda 环境和 python Flask 创建一个简单的 Web 应用程序,该应用程序显示来自 db 表的用户。

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>

没有错误,但是在本地主机上运行应用程序时,页面上没有显示列表。只有标题和要点。所以我猜 db.execute 正在返回一个空对象。

谁能告诉我出了什么问题?谢谢!

【问题讨论】:

  • sqlite3 如果找不到数据库,它将创建一个数据库,所以我猜你的路径“data.db”不是你所期望的。见stackoverflow.com/questions/57828286/…
  • sqlite3.version 是“此 [python] 模块的版本号”。如果你想比较数据库版本你必须使用sqlite3.sqlite_version
  • 问题是变量rowtuple而不是namedtuple,您需要根据元组中的索引以row[0]访问row["name"]。跨度>
  • 谢谢,我建议您使用 Flask-SQLAlchemy 进行数据库操作。它更容易且用途广泛。 (flask-sqlalchemy.palletsprojects.com/en/2.x)

标签: python sqlite flask


【解决方案1】:

你必须在获取结果之前打开游标

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)

附言rows 不是字典,它是tuple,使用zip 转换为dict: 如果用户中只有两列 rows=[dict(zip(('name', 'email'), row)) for row in rows]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-25
    • 1970-01-01
    • 2010-09-22
    • 2011-12-04
    • 1970-01-01
    • 2012-04-13
    相关资源
    最近更新 更多