【问题标题】:How to retrieve table names in a mysql database with Python and MySQLdb?如何使用 Python 和 MySQLdb 检索 mysql 数据库中的表名?
【发布时间】:2011-04-03 03:32:43
【问题描述】:

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

【问题讨论】:

  • 只是想知道为什么我投了反对票?我知道这个问题是一个新手问题,但我认为这些类型的问题在堆栈溢出时是允许的?

标签: python mysql mysql-python


【解决方案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

【讨论】:

    【解决方案2】:

    为了更完整一点:

    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)
    

    【讨论】:

    • Pitty...他们删除了整个网站。所以我删除了链接,感谢您的注意。
    • “USE”第 1 行或附近的错误语法错误:USE 门户
    • 很棒的答案
    • 谢谢!!当我们查询并想要结果时,我们总是需要使用 fetchall() 吗?
    【解决方案3】:

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

    【讨论】:

      【解决方案4】:

      显示表格

      15 个字符

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-08-20
        • 1970-01-01
        • 2014-08-15
        • 2016-04-18
        • 2013-05-22
        • 1970-01-01
        • 2012-03-22
        • 1970-01-01
        相关资源
        最近更新 更多