How do I get tables in postgres using psycopg2?

非 Y 不嫁゛ 提交于 2019-12-31 09:07:10

问题


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

I am using postgresql-8.4 psycopg2.


回答1:


This did the trick for me:

cursor.execute("""SELECT table_name FROM information_schema.tables
       WHERE table_schema = 'public'""")
for table in cursor.fetchall():
    print(table)



回答2:


pg_class stores all the required information.

executing the below query will return user defined tables as a tuple in a list

conn = psycopg2.connect(conn_string)
cursor = conn.cursor()
cursor.execute("select relname from pg_class where relkind='r' and relname !~ '^(pg_|sql_)';")
print cursor.fetchall()

output:

[('table1',), ('table2',), ('table3',)]



回答3:


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



回答4:


If you use psql, you can type:

\d

http://www.postgresql.org/docs/9.1/static/app-psql.html

If you are running SQL, you can type:

SELECT * FROM tables;

http://www.postgresql.org/docs/current/interactive/information-schema.html

If you want statistics about their usage, you can type:

SELECT * FROM pg_stat_user_tables;

http://www.postgresql.org/docs/current/interactive/monitoring-stats.html




回答5:


you can use this code for python 3

import psycopg2

conn=psycopg2.connect(database="your_database",user="postgres", password="",
host="127.0.0.1", port="5432")

cur = conn.cursor()

cur.execute("select * from your_table")
rows = cur.fetchall()
conn.close()


来源:https://stackoverflow.com/questions/10598002/how-do-i-get-tables-in-postgres-using-psycopg2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!