【问题标题】:Python psycopg2 postgres select columns including field namesPython psycopg2 postgres 选择包含字段名称的列
【发布时间】:2013-06-17 08:18:17
【问题描述】:

您好,我想从数据库中获取一个表,但要包含字段名称,以便我可以从列标题中使用它们,例如我不一定事先知道所有字段名称的熊猫

所以如果我的数据库看起来像

table test1

 a | b | c 
---+---+---
 1 | 2 | 3
 1 | 2 | 3
 1 | 2 | 3
 1 | 2 | 3
 1 | 2 | 3

我该怎么办

import psycopg2 as pq
cn = pq.connect('dbname=mydb user=me')
cr = cn.cursor()
cr.execute('SELECT * FROM test1;')
tmp = cr.fetchall()
tmp

这样 tmp 显示

[('a','b','c'),(1,2,3),(1,2,3),(1,2,3),(1,2,3),(1,2,3)]

谢谢

【问题讨论】:

  • @IgnacioVazquez-Abrams 不错。我本来建议从INFORMATION_SCHEMA 获取,但这更加灵活,因为它不仅限于表格。
  • 谢谢@IgnacioVazquez-Abrams 我不清楚如何用它来回答我的问题。 cr.description(test1) 不起作用。如果您将其放入答案中,我很乐意将其标记出来。

标签: python postgresql psycopg2


【解决方案1】:

如果您想要的是一个数据框,其中 db 表中的数据作为其值,而数据框列名称是您从 db 中读取的字段名称,那么这应该可以满足您的需求:

import psycopg2 as pq
cn = pq.connect('dbname=mydb user=me')
cr = cn.cursor()
cr.execute('SELECT * FROM test1;')
tmp = cr.fetchall()

# Extract the column names
col_names = []
for elt in cr.description:
    col_names.append(elt[0])

# Create the dataframe, passing in the list of col_names extracted from the description
df = pd.DataFrame(tmp, columns=col_names)

【讨论】:

    【解决方案2】:

    您可以使用两个循环案例,而不是使用 pandas:

    temp = []
    for x in result:
        temp2 = {}
        c = 0
        for col in cursor.description:
            temp2.update({str(col[0]): x[c]})
            c = c+1
        temp.append(temp2)
    print(temp)
    

    这将打印任何类似的内容:

    [{'column1':'foo1','column2':'foo1'},{'column1':'foo2','column2':'foo2'},...]
    

    希望对您有所帮助!干杯

    【讨论】:

    • 我认为这是最好的答案 - 简单而且确实有效。
    【解决方案3】:

    列名可以是cr.description[0][0]cr.description[1][0]等。如果您希望它与您显示的格式完全相同,您需要做一些工作来提取它并将其粘贴在结果集的前面。

    【讨论】:

      【解决方案4】:

      你也可以映射它看起来更好一点:

      cursor.execute(open("blah.sql", "r").read())
      data = cursor.fetchall()
      cols = list(map(lambda x: x[0], cursor.description))
      df = DataFrame(data, columns=cols)
      

      【讨论】:

        【解决方案5】:
        import psycopg2 as pq
        cn = pq.connect('dbname=mydb user=me')
        cr = cn.cursor()
        cr.execute('SELECT * FROM test1;')
        tmp = cr.fetchall() #Hi, these are your codes that build a connection to a psql server
        
        cols = []
        for col in tmp.description:
            cols.append(col[0]) #Collect all column names into an empty list, cols    
        tmp.insert(0, tuple(cols)) #insert elements by list.insert(index, new_item) method
        

        输出是

        [('a','b','c'),(1,2,3),(1,2,3),(1,2,3),(1,2,3),(1,2,3)]
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-10-13
          • 2018-10-29
          • 1970-01-01
          • 2021-01-14
          • 1970-01-01
          • 1970-01-01
          • 2016-02-14
          • 1970-01-01
          相关资源
          最近更新 更多