The Python Oracle

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

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------


Take control of your privacy with Proton's trusted, Swiss-based, secure services.
Choose what you need and safeguard your digital life:
Mail: https://go.getproton.me/SH1CU
VPN: https://go.getproton.me/SH1DI
Password Manager: https://go.getproton.me/SH1DJ
Drive: https://go.getproton.me/SH1CT


Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game Looping

--

Chapters
00:00 Easily Check If Table Exists With Python, Sqlalchemy On An Sql Database
00:33 Accepted Answer Score 26
00:52 Answer 2 Score 5
01:03 Thank you

--

Full question
https://stackoverflow.com/questions/6486...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #database #sqlalchemy

#avk47



ACCEPTED ANSWER

Score 26


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.




ANSWER 2

Score 5


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