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

前端 未结 8 2000
我在风中等你
我在风中等你 2020-12-08 18:24

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

相关标签:
8条回答
  • 2020-12-08 19:16

    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.

    0 讨论(0)
  • 2020-12-08 19:19

    The first answer did not work for me. I found success checking for the relation in pg_class:

    def table_exists(con, table_str):
        exists = False
        try:
            cur = con.cursor()
            cur.execute("select exists(select relname from pg_class where relname='" + table_str + "')")
            exists = cur.fetchone()[0]
            print exists
            cur.close()
        except psycopg2.Error as e:
            print e
        return exists
    
    0 讨论(0)
提交回复
热议问题