How to Print Out All Rows of a MySQL Table In Python



Python


In this article, we show how to print out all rows of 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 print out all rows of a MySQL table in Python is shown below.



So, this is all the code that is needed to print out all rows of 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. We need to know the number of rows the table has so that we can know how many rows to loop through in the for loop that follows.

Next, we have the for loop. This loops ranges from 0 to the length of the number of rows in the table. We print out each row with each increase in count of i. I goes from 0 to 1 to 2 to 3...up until the total number of rows in the table.

This way, we have all rows of the table printed out.

And this is how we can print out all of the rows of a MySQL table in Python.


Related Resources

How to Show All Tables of a MySQL Database in Python

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



HTML Comment Box is loading comments...