PostgreSQL
 sql >> Base de Dados >  >> RDS >> PostgreSQL

Verificando se uma tabela postgresql existe em python (e provavelmente em Psycopg2)


Que tal:
>>> import psycopg2
>>> conn = psycopg2.connect("dbname='mydb' user='username' host='localhost' password='foobar'")
>>> cur = conn.cursor()
>>> cur.execute("select * from information_schema.tables where table_name=%s", ('mytable',))
>>> bool(cur.rowcount)
True

Uma alternativa usando EXISTS é melhor porque não requer que todas as linhas sejam recuperadas, mas apenas que pelo menos uma dessas linhas exista:
>>> cur.execute("select exists(select * from information_schema.tables where table_name=%s)", ('mytable',))
>>> cur.fetchone()[0]
True