Reputation: 334
cursor.execute("""SELECT content, COUNT(*)
FROM Attachments
WHERE id = 123""")
results = cursor.fetchall()
print str(results[0][1]) # prints 3, meaning there are three rows returned
print results[1].content # IndexError: tuple index out of range
The query returns three rows, yet I am only able to access the first one.
Upvotes: 0
Views: 2162
Reputation: 880877
COUNT(*)
causes MySQL to aggregate all the rows into one. The content
field will be a single value from any of the aggregated rows.
To get all the rows, use
cursor.execute("""SELECT content
FROM Attachments
WHERE id = 123""")
results = cursor.fetchall()
Then you can look at len(results)
to obtain the count:
print(len(results)) # prints 3, meaning there are three rows returned
and get the second row using:
print(results[1])
Upvotes: 3
Reputation: 1406
I think you misunderstood how cursor.fetchall()
works. It returns a list of all rows, of which the length can be checked with
results = cursor.fetchall()
print len(results)
which should return 1 by the looks of the index error.
If you access results[0][1]
you are accessing whatever is at index 1 in the first row, which seems to be 3.
Upvotes: 1