Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

How can I determine if a table exists using the Psycopg2 Python library? I want a true or false boolean.

like image 402
Hellnar Avatar asked Dec 09 '09 14:12

Hellnar


People also ask

Does psycopg2 need PostgreSQL?

The psycopg2-binary package is meant for beginners to start playing with Python and PostgreSQL without the need to meet the build requirements.

What is psycopg2 used for in Python?

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.

How fetch data from PostgreSQL database in 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.


1 Answers

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 
like image 79
Peter Hansen Avatar answered Oct 11 '22 12:10

Peter Hansen