You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python+SQL购物车问题:重复添加商品无法更新数量,默认执行插入

问题排查与修复方案

核心错误点

  1. fetchone()返回值处理错误
    cursor.fetchone()的查询结果有两种情况:

    • 商品已在购物车:返回元组(如(2,)),直接执行quantity_selector += 1会触发TypeError,因为元组无法与整数相加。
    • 商品不在购物车:返回None,执行quantity_selector +=1同样触发TypeError。
      两种情况都会直接进入except分支执行插入逻辑,导致重复添加而非更新。
  2. 异常捕获范围过宽
    直接使用except:会捕获所有异常(包括数据库连接错误、SQL语法错误等),无法精准定位问题,还可能掩盖其他潜在bug。

修复后的代码

search_bar_2 = input("Enter what item you would like to look up >>> ")
try:
    sql = "SELECT * FROM Items_in_stock WHERE item_name = ?"
    cursor.execute(sql, (search_bar_2,))
    item = cursor.fetchone()
    print("id: ", item[0], "\nname of item: ", item[1], "\nquantity: ", item[2])
    add_to_cart = input("Would you like to add this item to your cart? (y/n) >>> ")
    if add_to_cart == 'y':
        # 先查询购物车中是否存在该商品
        sql3 = 'SELECT item_quantity FROM Shopping_cart WHERE item_name = ?'
        cursor.execute(sql3, (search_bar_2,))
        quantity_selector = cursor.fetchone()
        
        if quantity_selector is not None:
            # 商品已存在,取出元组中的数值并加1
            new_quantity = quantity_selector[0] + 1
            cursor.execute('UPDATE Shopping_cart SET item_quantity = ? WHERE item_name = ?', (new_quantity, search_bar_2))
            connection.commit()
            print("Updated cart successfully")
        else:
            # 商品不存在,执行插入
            add_cart = "INSERT INTO Shopping_cart(item_ID, item_name, item_quantity) VALUES (?, ?, ?)"
            item_values = (item[0], item[1], 1)
            cursor.execute(add_cart, item_values)
            connection.commit()
            print("Added to cart successfully")
except Exception as e:
    print(f"There is an error with the search item: {str(e)}") 

关键优化说明

  • 用条件判断替代异常捕获:不再依赖try-except区分商品是否存在,直接通过fetchone()返回值判断,逻辑更清晰,避免异常误触发。
  • 正确处理元组数据:商品存在时,从返回的元组中提取具体数值(quantity_selector[0])再执行加1操作。
  • 精准异常捕获:使用except Exception as e捕获异常并打印具体信息,便于调试。

内容的提问来源于stack exchange,提问作者Jeremy Panthier

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 22:05:17