如何在计数查询mysql(烧瓶)中修复输出
$
在我的导航栏中
def addcart():
cur = mysql.connection.cursor()
if 'uid' not in session:
noOfItems = 0
else:
uid = session['uid']
cur.execute("SELECT count(id_phone) FROM cart WHERE id_users = " + str(uid))
noOfItems = cur.fetchall()
return (noOfItems)
@app.route('/')
def index():
noOfItems = addcart()
return render_template("index.html", noOfItems=noOfItems)
OUTPUT:<a href="#" class="btn btn-more i-left">
<small><span class="badge badge-primary">{{noOfItems}}</span></small>
</a>
答案 0 :(得分:0)
def get_num_of_items():
cur = mysql.connection.cursor()
if 'uid' not in session:
num_of_items= 0
else:
uid = session['uid']
cur.execute("SELECT count(id_phone) FROM cart WHERE id_users = " + str(uid))
# cur.fetchone() return a dict with a single key:value pair
num_of_items = [v for v in cur.fetchone().values()][0]
return num_of_items
答案 1 :(得分:0)
您可以尝试将SQL SELECT语句更改为以下内容,看看是否可以解决您的问题:
cur.execute("SELECT COUNT(*) FROM cart WHERE id_users = " + str(uid) +";")
然后将以下内容更改为:
noOfItems = cur.fetchone()
return noOfItems[0]
noOfItems
将保存一个元组,其中包含一个元素,其值为COUNT(*)
,即您的购物车中用户ID为uid
的商品数。
希望有帮助!