PostgreSQL
 sql >> Database >  >> RDS >> PostgreSQL

Verifica se esiste una tabella postgresql sotto python (e probabilmente Psycopg2)

Che ne dici di:

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

Un'alternativa che utilizza EXISTS è migliore in quanto non richiede il recupero di tutte le righe, ma semplicemente che esiste almeno una di queste righe:

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