10

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

semiflex
  • 1,176
  • 3
  • 25
  • 44
  • 1
    `fetchall` will return *all* the rows the cursor has, not just the first. What are you actually trying to do? – Sean Vieira Feb 04 '16 at 16:00
  • 1
    I don't do anything with pyodbc, so this could be complete gibberish, but couldn't you do `cursor.fetchall()[:10]`? – zondo Feb 04 '16 at 16:04

2 Answers2

7

You insert:

row = cursor.fetchmany(10)

You can change the number in the parentheses to anything you want.

FlipperPA
  • 13,607
  • 4
  • 39
  • 71
semiflex
  • 1,176
  • 3
  • 25
  • 44
5

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)
ATLUS
  • 836
  • 6
  • 8