35

我有一个 SQL 数据库,想知道您使用什么命令来获取该数据库中的表名列表。

4

4 回答 4

84

更完整一点:

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)
于 2011-12-02T23:09:12.420 回答
10

显示表

15 个字符

于 2010-08-24T12:19:18.350 回答
7

show tables会有所帮助。这是文档

于 2010-08-24T12:20:01.233 回答
4

也可以通过使用下面的驱动程序执行单个查询从特定方案中获取表。

python3 -m pip install PyMySQL
import pymysql

# Connect to the database
conn = pymysql.connect(host='127.0.0.1',user='root',passwd='root',db='my_database')

# Create a Cursor object
cur = conn.cursor()

# Execute the query: To get the name of the tables from a specific database
# replace only the my_database with the name of your database
cur.execute("SELECT table_name FROM information_schema.tables WHERE table_schema = 'my_database'")

# Read and print tables
for table in [tables[0] for tables in cur.fetchall()]:
    print(table)

输出:

my_table_name_1
my_table_name_2
my_table_name_3
...
my_table_name_x
于 2020-10-24T18:02:12.430 回答