我正在嘗試對我的數據庫執行一些操作。表“訂單”在創建函數中獲取。但是為什麼它在 showtable() 函數中不起作用?這似乎是一個邏輯錯誤。我也想使用聚合函數。如何返回 query1() 的結果?
from flask import Flask, render_template, request, url_for, redirect
import sqlite3 as sql
app = Flask(__name__)
def dbconn():
con = sql.connect("onlineshop.db")
con.row_factory = sql.Row
cur = con.cursor()
return cur
@app.route('/createdb',methods = ['POST', 'GET'])
def create():
cur=dbconn()
cur.execute("CREATE TABLE orders(item TEXT, price REAL, cust_name TEXT)")
cur.execute("INSERT into orders (item, price, cust_name) values (?,?,?)",("Oximeter","50","Alice"))
cur.execute("INSERT into orders (item, price, cust_name) values (?,?,?)",("Sanitizer","20","Paul"))
cur.execute("INSERT into orders (item, price, cust_name) values (?,?,?)",("Mask","10","Anita"))
cur.execute("INSERT into orders (item, price, cust_name) values (?,?,?)",("Sanitizer","20","Tara"))
cur.execute("INSERT into orders (item, price, cust_name) values (?,?,?)",("Thermometer","30","Bob"))
cur.execute("INSERT into orders (item, price, cust_name) values (?,?,?)",("Mask","10","Alice"))
#return " Table is created."
cur.execute("select * from orders")
rows = cur.fetchall()
return render_template("onlineshoprecords.html", rows = rows)
@app.route('/showtable',methods = ['GET','POST'])
def showtable():
cur=dbconn()
cur.execute("SELECT * FROM orders")
rows = cur.fetchall()
return render_template("onlineshoprecords.html", rows = rows)
@app.route("/query1",methods = ['GET','POST'])
def query1():
cur=dbconn()
res1=cur.execute("select sum(price) from orders")
return f' result is :{res1}'
if __name__ == '__main__':
app.run(debug = True)
HTML
<!DOCTYPE html>
<head></head>
<body>
<table>
<tr>
<th>Item</th>
<th>Price</th>
<th>Customer Name</th>
</tr>
{% for row in rows %}
<tr align="center">
<td>{{row["item"]}} </td>
<td>{{row["price"]}}</td>
<td>{{row["cust_name"]}}</td>
</tr>
{% endfor %}
</table>
</body>
</html>
後
cur=dbconn()
cur.execute("SELECT * FROM orders")
rows = cur.fetchall()
rows
是list
的tuple
S,不是dict
s,如此的模板,你應該通過提供索引不是鍵來訪問它,如更換
<td>{{row["item"]}} </td>
<td>{{row["price"]}}</td>
<td>{{row["cust_name"]}}</td>
使用
<td>{{row[0]}}</td>
<td>{{row[1]}}</td>
<td>{{row[2]}}</td>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句