sql >> Base de Datos >  >> RDS >> PostgreSQL

Comprobando si existe una tabla postgresql bajo python (y probablemente Psycopg2)

¿Qué 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

Una alternativa que usa EXISTS es mejor porque no requiere que se recuperen todas las filas, sino simplemente que exista al menos una de esas filas:

>>> cur.execute("select exists(select * from information_schema.tables where table_name=%s)", ('mytable',))
>>> cur.fetchone()[0]
True