Saturday, October 15, 2016

Number of rows in an SQLite database with python

Hello there,

In this post, I will demonstrate a common issue of concern when working with an SQLite database in python.

As you already know, SQLite database is powered in python with a default module name: sqlite3. You don't need to install this as it already comes with every python installations since python version 2.5.

To use SQLite database in python there are basically six steps to take as follow:-

Step 1: Import sqlite3 module
Step 2: Connect to a database
Step 3: Create a cursor object
Step 4: Write an SQL query
Step 5: Commit changes
Step 6: Close database connection

Getting to know the number of rows in an SQLite database with python


This could be easily determined by use any SQLite GUI browser like SQLiteStudio, DB Browser, Navicat or SQLite Firefox browser add-on. But there is drawback in using the GUI, as you have to install a tool on your working machine and it the dataset within the database in big, it will take some effort to scroll down the table just to know the number of rows in the table.

If you already working in python, this can easily be done with few lines of code as follow.



As you can see above, my database "flights.db" has 6048 rows in its "airlines" table.

You will need to change step 2 and 4 above to match your database name and table name respectively.


Thanks for reading.

No comments:

Post a Comment