簡體   English   中英

如何使用 psycopg2 在 postgres 中獲取表?

[英]How do I get tables in postgres using psycopg2?

有人可以解釋一下如何獲取當前數據庫中的表嗎?

我正在使用 postgresql-8.4 psycopg2。

這對我有用:

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

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

問題是關於使用 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

這是一個包含connect()參數以及為輸出生成Python list()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.

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

如果你使用 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

您可以將此代碼用於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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM