首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用psycopg2在postgres中获取表?

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

Stack Overflow用户
提问于 2012-05-15 17:38:23
回答 7查看 54.6K关注 0票数 70

有人能解释一下如何在当前数据库中获取这些表吗?

我使用的是postgresql-8.4 psycopg2。

EN

回答 7

Stack Overflow用户

发布于 2014-06-28 09:39:04

这为我做了这个把戏:

代码语言:javascript
复制
cursor.execute("""SELECT table_name FROM information_schema.tables
       WHERE table_schema = 'public'""")
for table in cursor.fetchall():
    print(table)
票数 98
EN

Stack Overflow用户

发布于 2014-06-03 14:58:12

pg_class存储所有必需的信息。

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

代码语言:javascript
复制
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()

输出:

代码语言:javascript
复制
[('table1',), ('table2',), ('table3',)]
票数 38
EN

Stack Overflow用户

发布于 2014-02-01 01:02:59

问题是如何使用python的psycopg2来处理postgres。这里有两个方便的函数:

代码语言:javascript
复制
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
票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10598002

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档