python 如何使用psycopg2在postgres中获取表?

axzmvihb  于 2023-03-16  发布在  Python
关注(0)|答案(7)|浏览(189)

有谁能解释一下我怎么才能得到当前数据库中的表吗?
我用的是postgresql-8.4 psycopg 2.

mitkmikd

mitkmikd1#

这对我很有效:

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

prdp8dxp2#

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

wecizke33#

问题是如何使用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
bvn4nwqk

bvn4nwqk4#

下面是一个Python3代码片段,其中包含connect()参数,并生成Pythonlist()作为输出:

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.
46qrfjad

46qrfjad5#

虽然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()
qlzsbp2j

qlzsbp2j6#

打开光标后尝试此操作

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])
of1yzvn4

of1yzvn47#

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

相关问题