如何使用psycopg2在PostgreSQL中获取表格?

93

请问如何获取当前数据库中的表格?

我正在使用postgresql-8.4和psycopg2。

7个回答

127

这对我有帮助:

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

请查看以下链接:https://kb.objectrocket.com/postgresql/postgres-list-tables-with-python-1023 - hansrajswapnil

51

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',)]

3
我该如何将它转换为数组格式? - code-8
@code8888 cursor.fetchall() 可以获取表名,这对我很有效。 - GregarityNow

9
问题是关于使用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

该行代码"select exists(select relname from pg_class where relname='" + table_str + "')"可以用来检查表是否存在。 - wordsforthewise
你的返回类型 existstable_exists 中似乎有点混淆:如果表不存在,它会返回 False,但不确定如果表存在但为空是否会得到一个 falsey 值,以及如果表存在且非空,则返回表的第一行。最好将其默认为 None 而不是 False - smci
忘记在print语句后面加括号了 :) - Freek

2
这里有一个包含connect()参数并生成Pythonlist()输出的Python3代码片段:
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.

1

在打开游标后尝试这个

cur.execute("""
    SELECT table_name
    FROM information_schema.tables
    WHERE table_schema = 'public'
""")

# Fetch all the table names
table_names = cur.fetchall()

# Print the table names
for table_name in table_names:
    print(table_name[0])

谢谢,这对我有用,而且似乎是这里提出的最简单和最直接的解决方案。 - Rony Armon
谢谢,这对我有用,而且似乎是这里提出的最简单和最直接的解决方案。 - undefined

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

请不要编写这样的字符串。Python中的f""格式化具有特定用途。 - Chroma Funk

-9

您可以在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()

8
OP要求一种获取数据库中所有表的方法,而不是从表中获取记录。 - d3corator

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接