Hello By using the Psycopg2 of Python library, how can I determine if a table exists, getting a true or false boolean.
views:
276answers:
3
+2
A:
select exists(select relname from pg_class
where relname = 'mytablename' and relkind='r');
ChristopheD
2009-12-09 14:08:06
+2
A:
I don't know the psycopg2 lib specifically, but the following query can be used to check for existence of a table:
SELECT EXISTS(SELECT 1 FROM information_schema.tables
WHERE table_catalog='DB_NAME' AND
table_schema='public' AND
table_name='TABLE_NAME');
The advantage of using information_schema over selecting directly from the pg_* tables is some degree of portability of the query.
overthink
2009-12-09 14:09:52
+1
A:
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:
>>> cur.execute("select exists(select * from information_schema.tables where table_name=%s)", ('mytable',))
>>> cur.fetchone()[0]
True
Peter Hansen
2009-12-09 14:28:57
Close but better to use `exists()`. :)
jathanism
2009-12-09 14:36:51
I added that, but why is it "better"?
Peter Hansen
2009-12-09 14:41:58