如何使用 Python 和 MySQLdb 在 mysql 数据库中检索表名?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3556305/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to retrieve table names in a mysql database with Python and MySQLdb?
提问by Richard
I have an SQL database and am wondering what command you use to just get a list of the table names within that database.
我有一个 SQL 数据库,想知道您使用什么命令来获取该数据库中的表名列表。
采纳答案by Ty W
SHOW tables
显示表
15 chars
15 个字符
回答by Henning
show tableswill help. Here is the documentation.
show tables会有所帮助。这是文档。
回答by Remi
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)

