如何用Python和MySQLdb获取MySQL数据库中的表名?
我有一个SQL数据库,想知道用什么命令可以获取这个数据库里所有表的名字。
5 个回答
7
使用 show tables
这个命令可以帮你查看数据库里的所有表。想了解更多,可以看看这份文档。
86
为了更全面一点:
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)
现在有两个选择:
tables = cursor.fetchall() # return data from last query
或者遍历光标:
for (table_name,) in cursor:
print(table_name)
10
显示所有表格
15个字符