Mysql
 SQL >> Database >  >> RDS >> Mysql

Recuperare i nomi delle tabelle MySQL con Python e MySQLdb

Per essere un po' più completo:

import MySQLdb

connection = MySQLdb.connect(
    host = 'localhost',
    user = 'myself',
    passwd = 'mysecret')

cursor = connection.cursor()          # get the cursor
cursor.execute("USE mydatabase")      # select the database
cursor.execute("SHOW TABLES")         # execute 'SHOW TABLES'

Ora ci sono due possibilità:

tables = cursor.fetchall()            # return data from last query

oppure iterare sul cursore:

for (table_name,) in cursor:
    print(table_name)

In alternativa puoi interrogare information_schema, che è più esplicito e permette di filtrare per schema:

SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'mydatabase';

Ricorda di chiudere cursore e connessione (meglio con un context manager o in un blocco finally) per non esaurire le connessioni disponibili.