How do I get tables in postgres using psycopg2?

后端 未结 5 546
再見小時候
再見小時候 2021-01-31 01:48

Can someone please explain how I can get the tables in the current database?

I am using postgresql-8.4 psycopg2.

5条回答
  •  广开言路
    2021-01-31 02:15

    The question is about using python's psycopg2 to do things with postgres. Here are two handy functions:

    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
    
    def get_table_col_names(con, table_str):
    
        col_names = []
        try:
            cur = con.cursor()
            cur.execute("select * from " + table_str + " LIMIT 0")
            for desc in cur.description:
                col_names.append(desc[0])        
            cur.close()
        except psycopg2.Error as e:
            print e
    
        return col_names
    

提交回复
热议问题