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

前端 未结 8 2041
我在风中等你
我在风中等你 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:14

    The following solution is handling the schema too:

    import psycopg2
    
    with psycopg2.connect("dbname='dbname' user='user' host='host' port='port' password='password'") as conn:
        cur = conn.cursor()
        query = "select to_regclass(%s)"
        cur.execute(query, ['{}.{}'.format('schema', 'table')])
    
    exists = bool(cur.fetchone()[0])
    

提交回复
热议问题