Using Fetchall Fetchmany Fetchone()

 

Python cursor’s fetchall, fetchmany(), fetchone() to read records from database table:




what is the use of fetchall, fetchmany, fetchone?
 
 

cursor.fetchall() fetches all the rows of a query result. It returns all the rows as a list of tuples. An empty list is returned if there is no record to fetch.

cursor.fetchmany(size) returns the number of rows specified by size argument. When called repeatedly, this method fetches the next set of rows of a query result and returns a list of tuples. If no more rows are available, it returns an empty list.

cursor.fetchone() method returns a single record or None if no more rows are available
 
 
 
 

Fetch all rows from database table using cursor’s fetchall:

To fetch all rows from a database table, you need to follow these simple steps:

  • Create a database Connection from Python. Refer Python SQLite connection, Python MySQL connection, Python PostgreSQL connection.
  • Define the SELECT query. Here you need to know the table and its column details.
  • Execute the SELECT query using the cursor.execute() method.
  • Get resultSet (all rows) from the cursor object using a cursor.fetchall().
  • Iterate over the ResultSet using for loop and get column values of each row.
  • Close the Python database connection.
  • Catch any SQL exceptions that may come up during the process.
 
 
 
 

Retrieve a few rows from a table using:

cursor.fetchmany(size)

 
 Here size is the number of rows to be retrieved. This method fetches the next set of rows of a query result and returns a list of tuples. If no more rows are available, it returns an empty list.
 
 
 Cursor’s fetchmany() method returns the number of rows specified by size argument. the default value is 1. If the specified size is 100, then it returns 100 rows.
 
 
 

The syntax of the cursor’s fetchmany()

rows = cursor.fetchmany([size=cursor.arraysize])
 
 
 

Retrieve a single row from a table using cursor.fetchone:

 

Python DB API allows us to fetch only a single row. To fetch a single row from a result set we can use cursor.fetchone(). This method returns a single tuple.
 
 
 It can return a none if no rows are available in the resultset. cursor.fetchone() increments the cursor position by one and return the next row.
 
 
 
 
 
 
 
 
 
 

Comments

Popular posts from this blog

Queue in Java

Using lists , tuples, sets, dictionaries

Blog on Pytest