Python psycopg2 postgres选择包含字段名的列
嗨,我想从数据库中获取一个表,但要包括字段名,以便我可以从列标题中使用它们,例如熊猫,在熊猫中,我不一定事先知道所有字段名 所以如果我的数据库看起来像Python psycopg2 postgres选择包含字段名的列,python,postgresql,psycopg2,Python,Postgresql,Psycopg2,嗨,我想从数据库中获取一个表,但要包括字段名,以便我可以从列标题中使用它们,例如熊猫,在熊猫中,我不一定事先知道所有字段名 所以如果我的数据库看起来像 表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(
表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)]
谢谢列名可用作
cr.description[0][0]
,cr.description[1][0]
等。如果您希望它完全符合您显示的格式,您需要做一些工作来提取它并将其粘贴到结果集的前面。如果您想要的是一个数据框,其中db表中的数据作为其值,而dataframe列名是您从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)
您还可以在上面绘制一张看起来更漂亮的地图:
cursor.execute(open("blah.sql", "r").read())
data = cursor.fetchall()
cols = list(map(lambda x: x[0], cursor.description))
df = DataFrame(data, columns=cols)
可以使用两种循环情况,以不使用熊猫:
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'},...]
我希望这对你有帮助!干杯
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)]
@艾布拉姆斯尼斯。我本来打算建议从
信息_SCHEMA
中获取信息,但这样做更灵活,因为它不仅限于表格。谢谢@IgnacioVazquez Abrams,我不清楚如何使用它来回答我的问题<代码>cr.description(test1)不起作用。如果你把它写进一个答案中,我很乐意给它打分。我认为这是最好的答案——简单而且确实有效。