Checking if a postgresql table exists under python (and probably Psycopg2)

How about:

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

An alternative using EXISTS is better in that it doesn’t require that all rows be retrieved, but merely that at least one such row exists:

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)