pythondatabasesqlalchemy

Easily check if table exists with python, sqlalchemy on an sql database


Hello I am using sqlalchemy and pandas to process some data and then save everything to a table in an sql database. I am trying to find a quick easy and standardized way to check if a table exists in a database based on a table name.

I have found the has_table() function but no working examples. Does anyone has something like give "engine connection" & "table name"-> return true or false if table exists


Solution

  • With SQLAlchemy 1.4+ you can call has_table by using an inspect object, like so:

    import sqlalchemy as sa
    
    # … 
    
    engine = sa.create_engine(connection_uri)
    insp = sa.inspect(engine)
    print(insp.has_table("team", schema="dbo"))  # True (or False, as the case may be)
    

    For earlier versions of SQLAlchemy, see the other answer here.