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


               


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



Python


In this article, we show how to count the number of rows in a MySQL table in Python.

If you need to know how to install MySQL, see How to Install MySQL in Python 3. If you need to know how to connect to a MySQL database in Python, see How to Connect to a MySQL Database in Python.

So, the code to count the number of rows in a MySQL table in Python is shown below.



So, this is all the code that is needed to count the number of the rows in a MySQL table in Python.

So, the first thing we have to do is import the MySQLdb.

Once we have MySQLdb imported, then we create a variable named db. We set db equal to the MySQLdb.connect() function. This function will allow us to connect to a database. In side of this MySQLdb.connect() function are 4 parameters. These are, MySQLdb.connect("hostname", "username", "password", "database_name"). This line establishes connection with the database that you want.

We then create a variable named cursor, which we set equal to db.cursor(). This establishes a cursor for the database, which represents where the row that the cursor is currently pointing to. By default, the cursor will be on the first row, which is typically the names of each of the tables.

We then create a variable named number_of_rows, which we set equal to cursor.execute("SELECT * FROM Table_name). This fetches all of the rows from the table that you specify. Replace Table_name with the table that you want to find the number of rows for.

The number_of_rows variable stores the number of rows that the table contains.

To show the number of rows, all you have to do is type in the variable.



The table that I put in for my database has 81 rows. This is why you see 81 printed as the output.

And this is all that is required to find the number of rows in a MySQL table in Python.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...