How to Show All Tables of a MySQL Database In Python 


               


How to Show All Tables of a MySQL Database In Python



Python


In this article, we show how to show all tables of a MySQL database using 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 show all tables of a MySQL database in Python is shown below.



So, this is all the code that is needed to show all of the tables of a MySQL database in Python.

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

If you doing this through the pymysql module, then you first import the pymysql module and then install the MySQLdb from the pymysql module. We can then import the MySQLdb.

If you have the MySQLdb package directly installed, then the only import you need is MySQLdb and you leave out the first two lines (that contain pymysql).

So 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 result, which we set equal to cursor.fetchall(). This fetches all of the rows that the cursor is presently pointing to. Since the cursor, by default, points to the first row a table, result will contain all of the table names of each of the tables.

We then have a for loop that prints out all of the table names on a separate line.

The length of the variable result represents how many tables there are in the database. We then loop through each table name and print out each out until they are all printed out.

And this we can print out all of the tables of a MySQL database in Python.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...