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

如何将SQL表中的值转换为int?解决列表与整数相乘报错问题

解决方法

问题出在cursor.fetchall()的返回值上——它会把查询到的所有结果打包成列表,每个元素是对应行的元组(比如你查票价会得到[(35,)]这种格式),直接拿列表和整数相乘自然会报错。

你可以这么改:

方案1:用fetchone()获取单条结果(更适合你的场景,因为一个电影+场次应该对应唯一票价)

showTime = input("Enter showtime: ")
filmRequest = input("Enter the film you want to watch: ").title()

priceSelection_ = "SELECT price FROM films WHERE film = ? AND timings = ?"
parSel_ = (filmRequest, showTime)

cursor.execute(priceSelection_, parSel_)

# 只取第一条匹配结果(返回元组,比如(35,),如果没找到则返回None)
result = cursor.fetchone()

if result:
    # 提取元组里的第一个元素,转成int(如果票价是小数就用float)
    price = int(result[0])
    priceCalc_ = numTick_ * price
    print(priceCalc_)
else:
    print("未找到对应场次的电影信息")

方案2:如果一定要用fetchall()

如果你的查询可能返回多条结果(虽然你的场景不太可能),可以遍历列表提取数值:

x = cursor.fetchall()
if x:
    # 取第一条结果的第一个元素转int
    price = int(x[0][0])
    priceCalc_ = numTick_ * price
    print(priceCalc_)
else:
    print("未找到对应场次的电影信息")

核心就是:先从查询结果的列表/元组中提取出具体的票价数值,再转成int(或float),之后再和购票数量相乘。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 08:45:32