【发布时间】: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 -
问题是变量
row是tuple而不是namedtuple,您需要根据元组中的索引以row[0]访问row["name"]。跨度> -
查看docs.python.org/3/library/sqlite3.html中的row_factory
-
谢谢,我建议您使用 Flask-SQLAlchemy 进行数据库操作。它更容易且用途广泛。 (flask-sqlalchemy.palletsprojects.com/en/2.x)