Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/339.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python脚本中迭代Postgresql行?_Python_Postgresql_Pygresql - Fatal编程技术网

如何在Python脚本中迭代Postgresql行?

如何在Python脚本中迭代Postgresql行?,python,postgresql,pygresql,Python,Postgresql,Pygresql,我正在编写一个脚本,它从一个DB表中进行选择并对行进行迭代 在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

我正在编写一个脚本,它从一个DB表中进行选择并对行进行迭代

在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)


如何迭代查询结果?

我认为这是一样的,您必须创建游标,调用一些fetch并进行迭代,就像在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))
从中检索,您应该阅读

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

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

在google中搜索两秒钟就会得到:我的plpgsql文档链接不好,但这是什么DB-API模块?例如,据我所知,它很好地支持游标。我也建议使用
psycopg
。这个
pg
到底是什么?@LoïcFaure Lacroix在哪里可以看到对查询结果执行for循环的选项?@AnttiHaapala pg是python的一个包。你也可以在Loïc Faure Lacroix提供的链接中看到它。。。第一行是pg import DB的
,它在第一行显示
AttributeError:cursor
。据我所知,pos没有
cursor()
。好的。您使用的是经典的pygresapi。我认为最好使用它的DBAPI2.0接口。要执行此操作,必须导入
pgdb
,并将一些参数名称更改为
connect()
。然后我是否能够以以下方式访问数据:
行['x']
而不是
行[0]
?(像口述)。在MySQL中,我可以做:
connection.cursor(dictionary=True)
不知道这里的等价物是什么。我不这么认为。这是Python DB-API,您可以在其中从
光标读取列名、类型等。说明
,请参阅:和我编辑的代码示例PyGreSQL>=5.0行是命名元组,因此您可以使用row.xc是否可以将其更改为命令?所以我可以通过列名而不是列索引进行访问?@java将其更改为:q.dictresult()
q = db.query('select * from fruits')
q.getresult()