码迷,mamicode.com
首页 > 编程语言 > 详细

python 得到 postgres 查询结果 可以有列名

时间:2018-08-01 20:44:01      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:postgresq   exe   bsp   dbn   http   情况   情况下   pass   初始   

 1 import psycopg2
 2 import psycopg2.extras
 3 
 4 conn = psycopg2.connect(database=self.dbname, user=self.username, password=self.password,  host=self.host, port=self.port)
 5 cursor = self.conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
 6 sql = ""
 7 cursor.execute(sql)
 8 rows = self.cursor.fetchall()
 9 # 此时的 rows里面的元素 为 RowDict类型的结构,
10 for row in rows:
11     print row[某个列名]访问

参考:http://yuanjun.me/postgresql/pythoncao-zuo-postgresql#toc_5

在需要得到查询结果列名的情况下 需要初始化 cursor的时候特别注意,添加 

cursor_factory=psycopg2.extras.DictCursor

如此这样 也不影响,正常的遍历访问,如

a,b,c,d = row # a,b,c,d 都为具体的查询值

 

python 得到 postgres 查询结果 可以有列名

标签:postgresq   exe   bsp   dbn   http   情况   情况下   pass   初始   

原文地址:https://www.cnblogs.com/dasheng-maritime/p/9403520.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!