简体   繁体   中英

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

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

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))?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM