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

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

    I know you asked for psycopg2 answers, but I thought I'd add a utility function based on pandas (which uses psycopg2 under the hood), just because pd.read_sql_query() makes things so convenient, e.g. avoiding creating/closing cursors.

    import pandas as pd
    
    def db_table_exists(conn, tablename):
        # thanks to Peter Hansen's answer for this sql
        sql = f"select * from information_schema.tables where table_name='{tablename}'" 
        
        # return results of sql query from conn as a pandas dataframe
        results_df = pd.read_sql_query(sql, conn)
    
        # True if we got any results back, False if we didn't
        return bool(len(results_df))
    

    I still use psycopg2 to create the db-connection object conn similarly to the other answers here.

提交回复
热议问题