Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pyodbc - print first 10 rows (python)

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

like image 775
semiflex Avatar asked Feb 04 '16 15:02

semiflex


2 Answers

You insert:

row = cursor.fetchmany(10)

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

like image 138
semiflex Avatar answered Nov 12 '22 10:11

semiflex


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)
like image 30
ATLUS Avatar answered Nov 12 '22 09:11

ATLUS