I couldn\'t find any information about this in the documentation, but how can I get a list of tables created in SQLAlchemy?
I used the class method to create the tab
The metadata object that you created the tables with has that in a dictionary.
metadata.tables.keys()
Just this simple:
engine.table_names()
Also, to test whether a table exists:
engine.has_table(table_name)
from sqlalchemy import create_engine
engine = create_engine('postgresql://use:pass@localhost/DBname')
print (engine.table_names())
I was looking for something like this:
from sqlalchemy import create_engine
eng = create_engine('mysql+pymysql://root:password@localhost:3306', pool_recycle=3600)
q = eng.execute('SHOW TABLES')
available_tables = q.fetchall()
It does an execute and returns all of the tables.
update:
Postgres:
eng = create_engine('postgresql+psycopg2://root:password@localhost/
q = eng.execute('SELECT * FROM pg_catalog.pg_tables')
I'm solving same problem and found this post. After some try run, I would suggest use below to list all tables: (mentioned by zerocog)
metadata = MetaData()
metadata.reflect(bind=engine)
for table in metadata.sorted_tables:
print(table)
This is useful for direct table handling and I feel is recommended.
And use below code to get table names:
for table_name in engine.table_names():
print(table_name)
"metadata.tables" provides a Dict for table name and Table object. which would also be useful for quick query.
Within the python interpreter use db.engine.table_names()
$ python
>>> from myapp import db
>>> db.engine.table_names()