SQLAlchemy - Getting a list of tables

Viewed 144737

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 tables.

15 Answers
  • To get a list of all existing tables in DB:

As of SQLAlchemy 1.4: https://docs.sqlalchemy.org/en/14/core/reflection.html#fine-grained-reflection-with-inspector

from sqlalchemy import create_engine
from sqlalchemy import inspect
engine = create_engine('...')
insp = inspect(engine)
print(insp.get_table_names())

Older methods (engine.table_names()) yield:

SADeprecationWarning: The from_engine() method on Inspector is deprecated and will be removed in a future release. Please use the sqlalchemy.inspect() function on an Engine or Connection in order to acquire an Inspector. (deprecated since: 1.4)

  • To get a list of declared tables, use accepted answer: metadata.tables.keys()

Within the python interpreter use db.engine.table_names()

$ python
>>> from myapp import db
>>> db.engine.table_names()

Just this simple:

engine.table_names()

Also, to test whether a table exists:

engine.has_table(table_name)

This is what I'm using as of 2021-10-22:

import sqlalchemy as sql

engine = sql.create_engine("connection_string")

sql.inspect(engine).get_table_names()

The best way is to use inspect:

  1. Create the inspector and connect it to the engine
  2. Collect the names of tables within the database
  3. Collect Table columns names
from sqlalchemy import create_engine, inspect

engine = create_engine("sqlite:///../Resources/dow.sqlite")
conn = engine.connect()
inspector = inspect(conn)
inspector.get_table_names() #returns "dow"

columns = inspector.get_columns('dow')

for column in columns:
    print(column["name"], column["type"])

If you are using Flask-SQLAlchemy, you can get them from your db instance

[...]
db = SQLAlchemy(app)
db.engine.table_names() # you'll get a list of all the table names in your database

Complete example of displaying all column information. Assumes variable df contains a dataframe to be written to the SQL database.

from sqlalchemy import create_engine, inspect
from sqlalchemy_utils.functions import database_exists, create_database

engine = create_engine('sqlite:///mydb.sqlite', echo=True)

if not database_exists(engine.url):
    create_database(engine.url)
else:
    engine.connect()

df.to_sql('MyTable', con=engine, if_exists='replace', index=False) # index=False avoids auto-creation of level_0 (name tiebreaker)

inspector = inspect(engine)
table_names = inspector.get_table_names()
for table_name in table_names:
    print(f"Table:{table_name}")
    column_items = inspector.get_columns(table_name)
    print('\t'.join(n for n in column_items[0]))
    for c in column_items:
        assert len(c) == len(column_items[0])
        print('\t'.join(str(c[n]) for n in c))

I personally do this and it works:

from sqlalchemy import inspect
inspector = inspect(engine)
inspector.get_table_names()

It gives me all the names in my db.

Related