How to retrieve table names in a mysql database with Python and MySQLdb?

前端 未结 4 1754
醉话见心
醉话见心 2021-02-06 23:29

I have an SQL database and am wondering what command you use to just get a list of the table names within that database.

相关标签:
4条回答
  • 2021-02-06 23:37

    SHOW tables

    15 chars

    0 讨论(0)
  • 2021-02-06 23:40

    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)
    
    0 讨论(0)
  • 2021-02-06 23:44

    It is also possible to obtain tables from a specific scheme with execute the single query with the driver below.

    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)
    

    output:

    my_table_name_1
    my_table_name_2
    my_table_name_3
    ...
    my_table_name_x
    
    0 讨论(0)
  • 2021-02-06 23:49

    show tables will help. Here is the documentation.

    0 讨论(0)
提交回复
热议问题