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

 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 都为具体的查询值

 

posted @ 2018-08-01 19:36  百变小超  阅读(2270)  评论(0编辑  收藏  举报