74

有人可以解释一下如何获取当前数据库中的表吗?

我正在使用 postgresql-8.4 psycopg2。

4

7 回答 7

103

这对我有用:

cursor.execute("""SELECT table_name FROM information_schema.tables
       WHERE table_schema = 'public'""")
for table in cursor.fetchall():
    print(table)
于 2014-06-28T01:39:03.527 回答
40

pg_class 存储所有需要的信息。

执行以下查询将返回用户定义的表作为列表中的元组

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()

输出:

[('table1',), ('table2',), ('table3',)]
于 2014-06-03T06:58:12.460 回答
8

问题是关于使用 python 的 psycopg2 来处理 postgres。这里有两个方便的功能:

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
于 2014-01-31T17:02:58.607 回答
2

这是一个Python3包含connect()参数并生成Python list()输出的片段:

conn = psycopg2.connect(host='localhost', dbname='mySchema',
                        user='myUserName', password='myPassword')
cursor = conn.cursor()

cursor.execute("""SELECT relname FROM pg_class WHERE relkind='r'
                  AND relname !~ '^(pg_|sql_)';""") # "rel" is short for relation.

tables = [i[0] for i in cursor.fetchall()] # A list() of tables.
于 2021-06-11T23:03:24.703 回答
1

虽然它已被 Kalu 回答,但提到的查询从 postgres 数据库返回表 + 视图。如果您只需要表格而不需要视图,那么您可以在查询中包含 table_type -

        s = "SELECT"
        s += " table_schema"
        s += ", table_name"
        s += " FROM information_schema.tables"
        s += " WHERE"
        s += " ("
        s += " table_schema = '"+SCHEMA+"'"
        s += " AND table_type = 'BASE TABLE'"
        s += " )"
        s += " ORDER BY table_schema, table_name;"

        db_cursor.execute(s)
        list_tables = db_cursor.fetchall()
于 2021-10-26T06:20:26.893 回答
-1

如果你使用 psql,你可以输入:

\d

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

如果您正在运行 SQL,则可以键入:

SELECT * FROM tables;

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

如果您想要有关其使用情况的统计信息,您可以键入:

SELECT * FROM pg_stat_user_tables;

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

于 2012-05-15T11:06:09.880 回答
-7

您可以将此代码用于 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()
于 2018-09-22T18:51:51.800 回答