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

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-01
  • 2022-12-23
  • 2022-02-02
猜你喜欢
  • 2021-12-02
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-15
  • 2021-06-02
  • 2022-12-23
相关资源
相似解决方案