Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve table names in a mysql database with Python and MySQLdb?

I have an SQL database and am wondering what command you use to just get a list of the table names within that database.

like image 805
Richard Avatar asked Aug 24 '10 12:08

Richard


People also ask

How do I get a list of table names in MySQL?

The syntax to get all table names with the help of SELECT statement. mysql> use test; Database changed mysql> SELECT Table_name as TablesName from information_schema.

How do I get a list of table names in a database?

In MySQL, there are two ways to find the names of all tables, either by using the "show" keyword or by query INFORMATION_SCHEMA. In the case of SQL Server or MSSQL, You can either use sys. tables or INFORMATION_SCHEMA to get all table names for a database.


2 Answers

To be a bit more complete:

import MySQLdb  connection = MySQLdb.connect(                 host = 'localhost',                 user = 'myself',                 passwd = 'mysecret')  # create the connection  cursor = connection.cursor()     # get the cursor   cursor.execute("USE mydatabase") # select the database  cursor.execute("SHOW TABLES")    # execute 'SHOW TABLES' (but data is not returned) 

now there are two options:

tables = cursor.fetchall()       # return data from last query 

or iterate over the cursor:

 for (table_name,) in cursor:         print(table_name) 
like image 129
Remi Avatar answered Sep 25 '22 08:09

Remi


SHOW tables

15 chars

like image 34
Ty W Avatar answered Sep 26 '22 08:09

Ty W