how to fetch data from mysql as int instead of tuple in python

this is my code:

x=va1.get()
y=va2.get()

conn=pymysql.connect(host='localhost',user="root",passwd="",db='billing')
q=conn.cursor()
q.execute(f"SELECT stock FROM items WHERE barcode = {x}")
rr=q.fetchone()
for i in rr:
         if y<=i[0]:
               messagebox.showinfo("Stock","You only have f{rr} to buy in f{x}")
         else:
               print("You have enough stock to buy this item")

va1 and va2 are variables from entries

this is my error:

if y<=i[0]: TypeError: 'int' object is not subscriptable

2 answers

  • answered 2019-12-15 02:35 Michael

    It looks like .fetchone() is only returning a single item.

    Within that item, what you're iterating through look like they're ints. This means that i doesn't have an index.

    Have you tried fetchall instead. (Or if it's a lot of data, fetchmany(n))?

  • answered 2019-12-15 02:39 OneCricketeer

    You're only selecting one column, so you can do this, assuming that you always will get a database result

    stock =q.fetchone()[0]
    

    If you don't get any result, then you'll need to check for it and assign some default

    rr =q.fetchone()
    stock = -1 if rr is None else rr[0]
    

    And you'd remove the for loop