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

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

    Expanding on the above use of EXISTS, I needed something to test table existence generally. I found that testing for results using fetch on a select statement yielded the result "None" on an empty existing table -- not ideal.

    Here's what I came up with:

    import psycopg2
    
    def exist_test(tabletotest):
    
        schema=tabletotest.split('.')[0]
        table=tabletotest.split('.')[1]
        existtest="SELECT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = '"+schema+"' AND table_name = '"+table+"' );"
    
        print('existtest',existtest)
    
        cur.execute(existtest) # assumes youve already got your connection and cursor established
    
        # print('exists',cur.fetchall()[0])
        return ur.fetchall()[0] # returns true/false depending on whether table exists
    
    
    exist_test('someschema.sometable')
    

提交回复
热议问题