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
or in Python using psycopg2 : cur. execute( """ SELECT COUNT(*) = 1 FROM pg_tables WHERE tablename = 'my_table'; """ ) exists = cur. fetchone()[0] print(exists) True if exists is False: # table does not exist ...
To check if a table exists in SQL Server, you can use the INFORMATION_SCHEMA. TABLES table. You can use this table with an IF THEN clause do determine how your query responds whether or not a table exists.
To check if table exists in a database you need to use a Select statement on the information schema TABLES or you can use the metadata function OBJECT_ID(). The INFORMATION_SCHEMA. TABLES returns one row for each table in the current database.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With