从Flask应用程序连接到sqlite3数据库,并在网页上打印数据



我正在使用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返回一个空对象。

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

必须在获取结果前打开光标

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)

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

最新更新