【问题标题】:How do I get tables in postgres using psycopg2?如何使用 psycopg2 在 postgres 中获取表?
【发布时间】:2012-05-22 19:16:58
【问题描述】:

谁能解释一下如何获取当前数据库中的表?

我正在使用 postgresql-8.4 psycopg2。

【问题讨论】:

    标签: python psycopg2 postgresql-8.4


    【解决方案1】:

    这对我有用:

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

    【讨论】:

      【解决方案2】:

      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】:

      问题是关于使用 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 + "')" 行用于检查表是否存在
      • 您从table_exists 中返回的exists 似乎有点混乱:如果表不存在,它会返回False,如果表确实存在,则不确定您是否得到错误值空,如果表存在且非空,则为表的第一行。最好默认为None 而不是False
      • 打印语句后缺少括号:)
      【解决方案4】:

      这是一个Python3 sn-p,其中包含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.
      

      【讨论】:

        【解决方案5】:

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

        【讨论】:

          【解决方案6】:

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

          【讨论】:

            【解决方案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()
            

            【讨论】:

            • OP 要求一种方法来获取数据库的所有表,而不是从表中获取记录
            猜你喜欢
            • 1970-01-01
            • 2022-12-03
            • 2020-09-01
            • 1970-01-01
            • 2021-10-28
            • 1970-01-01
            • 2011-10-09
            • 1970-01-01
            • 2021-12-31
            相关资源
            最近更新 更多