如何修复计数查询MySQL中的输出(烧瓶)

时间:2019-02-21 12:46:30

标签: python mysql flask

如何在计数查询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>

2 个答案:

答案 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的商品数。

希望有帮助!