Python SQLite cursor.fetchall() Function
The Python cursor.fetchall() function retrieves all the rows from the database. When we execute a query using the cursor object, then the results are stored in the cursor.
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.
If there are no rows left to retrieve, then this function returns an empty list.
Syntax
Following is the syntax for the cursor.fetchall() function.
rows = cursor.fetchall()
Parameters
This function doesn't take any parameters.
Return Value
This function returns the tuple from the database.
| 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 1
Consider the above example to fetch the given rows from the table using cursor.fetchall() function.
cursor.execute("SELECT * FROM employees WHERE ID = 3, 4")
print(cursor.fetchall())
Output
The result is generated as follows −
| ID | Name | Age | Salary | City | Country |
|---|---|---|---|---|---|
| 3 | Sumit | 45 | 4500.00 | Muscat | Oman |
| 4 | Kaushik | 25 | 2500.00 | Kolkata | India |
Example 2
In the example below, we are selecting a row with an ID of 11, which doesn't exist. By using the cursor.fetchall() function, this function returns an empty set.
cursor.execute("SELECT * FROM employees WHERE ID = 11")
x = cursor.fetchall()
print(x)
Output
The result is generated as follows −
[]
python_modules.htm