How can I determine if a table exists using the Psycopg2 Python library? I want a true or false boolean.
The psycopg2-binary package is meant for beginners to start playing with Python and PostgreSQL without the need to meet the build requirements.
Python psycopg2 module APIs No. This API opens a connection to the PostgreSQL database. If database is opened successfully, it returns a connection object. This routine creates a cursor which will be used throughout of your database programming with Python.
You can fetch data from PostgreSQL using the fetch() method provided by the psycopg2. The Cursor class provides three methods namely fetchall(), fetchmany() and, fetchone() where, The fetchall() method retrieves all the rows in the result set of a query and returns them as list of tuples.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With