Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 574
KZiovas Avatar asked Nov 16 '20 16:11

KZiovas


People also ask

How do I check if a table exists in Python using SQL Server?

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 ...

How do you test if a table exists in SQL?

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.

How do you check if a table exists or not?

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.


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.

like image 82
Gord Thompson Avatar answered Oct 15 '22 14:10

Gord Thompson


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
like image 33
KZiovas Avatar answered Oct 15 '22 14:10

KZiovas