为什么我可以返回完整的查询结果,但不能返回其中的指定项



我(python新手(正试图使用Tkinter创建一个简单的程序,从文本框中获取产品代码,并从数据库中返回成本。

import pyodbc
from tkinter import *
root = Tk()
root.title('Cost Checker')
root.geometry("250x100")
#create connection
cnxn = pyodbc.connect("Driver={ODBC Driver 17 for SQL Server};"
"Server=XXXXXXXXXX.XXXXXXX.XXX;"
"Database=DataLake;"
"Trusted_Connection=yes;")
#function to run SQL 
def Check():
cursor = cnxn.cursor()
cursor.execute('SELECT Products.ProductNumber, Products.EnglishDescription, Products.CurrentCost
FROM DataLake.dbo.Products Products
WHERE (Products.ProductNumber = ' + "'" + str(myTextbox.get()) + "'" + ')')
list = cursor.fetchall()
result = Label(root, text ="The cost of " + str(myTextbox.get()) + " is " + str(list))
result.pack()
myLabel = Label(root, text="Enter a product number:")
myLabel.pack()
myTextbox = Entry(root, width=30)
Entry.focus(myTextbox)
myTextbox.pack()
myButton = Button(root, text="Submit", command = Check) #
myButton.pack()
root.mainloop()

我正在努力从清单中找出成本。

我得到的结果是";X的成本是[('X','X描述',十进制('19.99'(]〃;。所以我知道查询正在返回一个结果。

期望的结果是";X的成本是19.99〃;。

我试过更换

result = Label(root, text ="The cost of " + str(myTextbox.get()) + " is " + str(list))

result = Label(root, text ="The cost of " + str(myTextbox.get()) + " is " + str(list[2]))

拉出第三个元素,但我得到了一个列表索引超出范围的错误。

Exception in Tkinter callback
Traceback (most recent call last):
File "C:Users******AppDataLocalProgramsPythonPython39-32libtkinter__init__.py", line 1892, in __call__
return self.func(*args)
File "C:pythonstuffCostCheckerGUI.py", line 23, in Check
result = Label(root, text ="The cost of " + str(myTextbox.get()) + " is " + str(list[2]))

这可能很简单,但当我搜索";IndexError:列表索引超出范围";,所有结果都是指试图提取一个不存在的索引。我知道成本是[2]而不是[3]。

提前感谢

newpy

请注意其中的括号:[('X','X Description', Decimal('19.99'))]

这不是一个长度为三的列表;它是一个长度为1的列表,包含一个长度3的元组。您需要对其进行两次索引:一次获取内部元组,然后再次从元组中获取数据:

tup = list[0]  # Get tuple
dec = tup[2]  # Get decimal

或者,组合:

dec = list[0][2]

此外,请不要将list用作名称。这是一个内置的函数,如果您决定在同一范围内使用内置的list函数,那么隐藏它将导致以后的痛苦。

相关内容