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

╄→尐↘猪︶ㄣ 提交于 2019-12-12 08:19:55

问题


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


回答1:


SHOW tables

15 chars




回答2:


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)



回答3:


show tables will help. Here is the documentation.



来源:https://stackoverflow.com/questions/3556305/how-to-retrieve-table-names-in-a-mysql-database-with-python-and-mysqldb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!