I'm trying to print the first 10 rows using pyodbc. I know how to get the first record by using the following:
row = cursor.fetchall()
I tried changing this to:
row = cursor.fetchten()
but this didn't work. Is there anything else I can do??
You insert:
row = cursor.fetchmany(10)
You can change the number in the parentheses to anything you want.
Based on the documentation found on this page, you've got two options for returning lists. You have the fetchall()
method and the fetchmany()
method. In either case, you're returned a list of rows to work with.
Regarding the fetchall()
method and piggybacking off of what zondo said, the following works quickly and efficiently:
rows = cursor.fetchall()[:10] # to get the first 10
rows = cursor.fetchall()[-10::1] # to get the last 10
Alternatively, you can loop over the rows as many times you need to get the results you need:
rows = cursor.fetchall()
for idx in range(10): #[0, 1, ..., 9,]
print(rows[idx]) # to get the first 10
print(rows[(len(ray)-idx)]) # to get the last 10
There is also the fetchmany()
method in the same documentation, defined as follows: cursor.fetchmany([size=cursor.arraysize]) --> list
The brackets indicate optional parameters, so you do not need to include the size. But since you want 10, you will pass 10 into the size parameter. Example:
rows = cursor.fetchmany(size=10)
for row in rows:
print(row)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With