如何将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
相关产品推荐
相关产品推荐

