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

Viewed 9916

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

2 Answers

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.

so I made this function based on this idea from the first reposnse:

def table_exists(engine,name):
    ins = inspect(engine)
    ret =ins.dialect.has_table(engine.connect(),name)
    print('Table "{}" exists: {}'.format(name, ret))
    return ret
Related