14

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

0

3 Answers 3

27

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.

Sign up to request clarification or add additional context in comments.

7 Comments

that is almost correct I tested it but it didnt run for me I dont know why I had to add insp.dialect.has_table.
What dialect are you using? The above works for me with mssql+pyodbc.
could it be different versions of the library? because the inspector object does not have a has_table funtion at all
@Freude - The schema= keyword argument defaults to None so you can simply omit it.
This also works for the version 2.0 engine.
|
4

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

1 Comment

sqlalchemy .inspect for those who wonders.
0

NOTE: This method is discouragued by SQLAlchemy, is published only for third party dialects or a plugin, use at this conditions.

For SQLAlchemy==2.0.25

from sqlalchemy import create_engine
from sqlalchemy.engine import URL

url = URL.create(drivername=drivername,
                              username=youruser,
                              password=yourpass,
                              host=yourhost,
                              database=yourdbname)

engine = create_engine(url, echo=True)

if engine.dialect.has_table(table_name=YOURTABLENAME,connection=engine.connect()):
    echo "table exist"

1 Comment

Using this method is explicitly discouraged in the docs: "This method is used internally by SQLAlchemy, and is published so that third-party dialects may provide an implementation. It is not the public API for checking for table presence. Please use the Inspector.has_table() method."

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.