如何使用Python和MySQLdb检索mysql数据库中的表名?

时间:2010-08-24 12:18:02

标签: python mysql mysql-python

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

4 个答案:

答案 0 :(得分:58)

更完整一点:

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)

答案 1 :(得分:9)

SHOW表

15个字符

答案 2 :(得分:8)

show tables会有所帮助。 Here is the documentation

答案 3 :(得分:1)

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

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