How to Count the Number of Rows of a Given SQLite Table using Python?
Last Updated :
28 Apr, 2021
In this article, we will discuss how we can count the number of rows of a given SQLite Table using Python. We will be using the cursor_obj.fetchall() method to do the same. This method 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.
To create the database, we will execute the following code:
Python3
import sqlite3
connection_obj = sqlite3.connect( 'geek.db' )
cursor_obj = connection_obj.cursor()
cursor_obj.execute( "DROP TABLE IF EXISTS GEEK" )
table =
cursor_obj.execute(table)
connection_obj.execute(
)
connection_obj.execute(
)
connection_obj.execute(
)
connection_obj.execute(
)
connection_obj.execute(
)
connection_obj.execute(
)
connection_obj.execute(
)
connection_obj.commit()
connection_obj.close()
|
Output:
So by finding the length of this list which is return by fetchall(), we get the count of the total number of rows.
Python3
import sqlite3
connection_obj = sqlite3.connect( 'geek.db' )
cursor_obj = connection_obj.cursor()
print ( "Count of Rows" )
cursor_obj.execute( "SELECT * FROM GEEK" )
print ( len (cursor_obj.fetchall()))
connection_obj.commit()
connection_obj.close()
|
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...