After recieving data from mysql connector, when I try to iterate over the list, python keeps telling me the data is of type int:
The execute() and fetchall() statements:
def top_sellers(self):
q = '''select Item, sum(Quantity) from purchases group by Item;'''
self.cursor.execute(q)
s = self.cursor.fetchall()
print(s)
print(type(s))
for i in len(s):
print(i)
The above code exits with:
[('beep', Decimal('3')), ('item1', Decimal('39')), ('Mask', Decimal('53')), ('Mask1', Decimal('2'))]
<class 'list'>
Traceback (most recent call last):
File "/data/data/com.termux/files/home/projekt-red/index.py", line 326, in <module>
main(id, password)
File "/data/data/com.termux/files/home/projekt-red/index.py", line 324, in main
x.load_prompt(acc_type)
File "/data/data/com.termux/files/home/projekt-red/index.py", line 301, in load_prompt
self.stats()
File "/data/data/com.termux/files/home/projekt-red/index.py", line 243, in stats
self.top_sellers()
File "/data/data/com.termux/files/home/projekt-red/index.py", line 265, in top_sellers
for i in len(list(s)):
TypeError: 'int' object is not iterable
len(s)
is an integer, which is not iterable.
If you want to iterate n
times, with n = len(s)
, you need to replace len(s)
by range(len(s))
like so:
def top_sellers(self):
q = '''select Item, sum(Quantity) from purchases group by Item;'''
self.cursor.execute(q)
s = self.cursor.fetchall()
print(s)
print(type(s))
for i in range(len(s)):
print(i)
Edit:
This will print all the indices. If you want to print the results stored in s
, then simply remove the len()
and range()
, just keeping for i in s
. Or alternatively, keep it as above and replace the print statement by print(s[i])
.