如何在 Python 脚本中遍历 Postgresql 行?

How to iterate over Postgresql rows in a Python script?

我正在编写一个脚本,它从数据库 table 中选择并遍历行。

在MySQL我会做:

import MySQLdb
db_mysql=MySQLdb.Connect(user=...,passwd=...,db=..., host=...)
cur = db_mysql.cursor(MySQLdb.cursors.DictCursor)
cur.execute ("""SELECT X,Y,Z FROM tab_a""")
for row in crs.fetchall () :
     do things...

但我不知道如何在 PostgreSQL 中执行此操作。 基本上这个问题可能是如何翻译上面的 MySQL 代码以与 PostgreSQL 一起工作。

这是我目前所拥有的(我正在使用 PyGreSQL)。

import pg
pos = pg.connect(dbname=...,user=...,passwd=...,host=..., port=...)
pos.query("""SELECT X,Y,Z FROM tab_a""")

如何遍历查询结果?

我认为它是一样的,你必须像在 MySQL:

中一样创建游标,调用一些提取和迭代
import pgdb
pos = pgdb.connect(database=...,user=...,password=...,host=..., port=...)
sel = "select version() as x, current_timestamp as y, current_user as z"
cursor = db_conn().cursor()
cursor.execute(sel)
columns_descr = cursor.description
rows = cursor.fetchall()
for row in rows:
    x, y, z = row
    print('variables:')
    print('%s\t%s\t%s' % (x, y, z))
    print('\nrow:')
    print(row)
    print('\ncolumns:')
    for i in range(len(columns_descr)):
        print('-- %s (%s) --' % (columns_descr[i][0], columns_descr[i][1]))
        print('%s' % (row[i]))
    # this will work with PyGreSQL >= 5.0
    print('\n testing named tuples')
    print('%s\t%s\t%s' % (row.x, row.y, row.z))

取自 http://www.pygresql.org/contents/tutorial.html,您应该阅读。

q = db.query('select * from fruits')
q.getresult()

结果是一个Python元组列表,eardh元组包含一行,你只需要遍历列表并迭代或索引元组。