Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
409 views
in Technique[技术] by (71.8m points)

sqlite - How to display information from database sqlite3 using GUI Tkinter in Python in a specific format?

I am trying to retrieve information from the database and display it in this certain way:

Name: Batman

Price: £ 18

But I am getting this error: "TypeError: 'int' object is not subscriptable."

How can I fix that?

c.execute("SELECT name, price FROM products WHERE id=02")
    records = c.fetchone()
    # print(records)

    print_products = ''
    for record in records:
        print_products += 'Name:' + str(record[0]) + '
' + 'Price: £' + str(record[1])

    query_label = Label(frame, fg='darkblue', bg='darkgray', text=print_products)
    query_label.pack()
question from:https://stackoverflow.com/questions/65927665/how-to-display-information-from-database-sqlite3-using-gui-tkinter-in-python-in

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Since you only fetch one record from the result, records is a tuple of column values. Then you use for record in records:, it means record is a column value that may be an integer. So using record[0] will raise the mentioned exception.

Actually you don't need the for loop at all:

c.execute("SELECT name, price FROM products WHERE id=02")
record = c.fetchone()

# check whether record exists
if record:
    print_products = 'Name:' + str(record[0]) + '
' + 'Price: £' + str(record[1])

    query_label = Label(frame, fg='darkblue', bg='darkgray', text=print_products)
    query_label.pack()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...