Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to Count the Number of Rows in a MySQL Table in Python?

  • Last Updated : 12 Nov, 2020

MySQL server is an open-source relational database management system which is a major support for web-based applications. Databases and related tables are the main component of many websites and applications as the data is stored and exchanged over the web. In order to access MySQL databases from a web server we use various modules in Python such as PyMySQL, mysql.connector, etc. 

In this article, we are going to get the number of rows in a specific MySQL table in a Database. First, we are going to connect to a database having a MySQL table. The SQL query that is going to be used is:

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

SELECT * FROM table-name

 And finally, display the number of rows in the table.



Below are some programs which depict how to count the number of rows from a MySQL table in a Database:

Example 1

Below is the table geeksdemo in database geek which is going to be accessed by a Python script:

Below is the program to get the number of rows in a MySQL table:

Python3




# import required modules
import pymysql
pymysql.install_as_MySQLdb()
import MySQLdb
  
# connect python with mysql with your hostname, 
# username, password and database
db= MySQLdb.connect("localhost", "root", "", "geek")
  
# get cursor object
cursor= db.cursor()
  
# get number of rows in a table and give your table
# name in the query
number_of_rows = cursor.execute("SELECT * FROM geeksdemo")
  
# print the number of rows
print(number_of_rows)

Output:



Example 2:

Here is another example to get the number of rows from a table in a given database, below is the table scheme and rows:

Below is the python script to get row count from the table TechCompanies:

Python3




# import required modules
import pymysql
pymysql.install_as_MySQLdb()
import MySQLdb
  
# connect python with mysql with your hostname, 
# username, password and database
db= MySQLdb.connect("localhost", "root", "", "techgeeks")
  
# get cursor object
cursor= db.cursor()
  
# get number of rows in a table and give your table
# name in the query
number_of_rows = cursor.execute("SELECT * FROM techcompanies")
  
# print the number of rows
print(number_of_rows)

Output:




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!