The python cursor.fetchmany() function fetches the next rows of a database. This function returns an empty list when there are no rows available. It retrieves to fetch as many rows as are available.
A cursor is an object that is used to interact with the database. This function allows us to execute SQL queries. It returns tuples representing a row. A Cursor is used for executing commands and retrieving query results.
SyntaxFollowing is the basic syntax for the cursor.fetchmany() function.
cursor.fetchmany(size = cursor.arraysize)Parameters
The size of the parameter determines the number of rows to retrieve.
Return ValueThis function returns a list of tuples; each tuple represents a row from the dataset. If there are less number of rows available then this function will return only the specified rows.
ExampleConsider the following EMPLOYEES table which stores employees ID, Name, Age, Salary, City and Country −
ID Name Age Salary City Country 1 Ramesh 32 2000.00 Maryland USA 2 Mukesh 40 5000.00 New York USA 3 Sumit 45 4500.00 Muscat Oman 4 Kaushik 25 2500.00 Kolkata India 5 Hardik 29 3500.00 Bhopal India 6 Komal 38 3500.00 Saharanpur India 7 Ayush 25 3500.00 Delhi India Example 1Consider the above example of fetching the number of rows at a time using cursor.fetchmany() function.
cursor.execute("SELECT * FROM employees") rows = cursor.fetchmany(size = 2) for row in rows: print(row)Output
The result is obtained as follows −
ID Name Age Salary City Country 1 Ramesh 32 2000.00 Maryland USA 2 Mukesh 40 5000.00 New York USA Example 2In the example below, we are going to fetch specified rows with particular columns using cursor.fetchmany() function.
cursor.execute("SELECT Name, City FROM employees) rows = cursor.fetchmany(size = 3) for row in rows: print(row)Output
We will get the output as follows −
Name City Ramesh Maryland Mukesh New York Sumit Muscat Example 3In the below example, we are fetching all columns from the employee table where the country is 'India' using cursor.fetchmany() function.
cursor.execute("SELECT * FROM employees WHERE country = 'India'") rows = cursor.fetchmany(size = 4) for row in rows: print(row)Output
The result is generated as follows −
ID Name Age Salary City Country 4 Kaushik 25 2500.00 Kolkata India 5 Hardik 29 3500.00 Bhopal India 6 Komal 38 3500.00 Saharanpur India 7 Ayush 25 3500.00 Delhi Indiapython_modules.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4