检索后更新postgresql

时间:2015-06-05 17:06:34

标签: python postgresql psycopg2

您好我使用psycopg2服务器端游标功能从PostgreSQL中检索大型数据集。我需要获取行(然后用它做一些事情),然后更新一个布尔列以指示它已被处理。这是我到目前为止所尝试的: -

import psycopg2

import psycopg2.extras
import sys

query = """
    select * from exports;
"""


con = psycopg2.connect("dbname='test' user='postgres' password='*****'")

cursor = con.cursor('server_side_cursor', cursor_factory=psycopg2.extras.DictCursor)
cursor.execute(query)

while True:
    rows = cursor.fetchmany(5000)
    if not rows:
        break
    row_count = 0
    for row in rows:
        row_count += 1
        print "row: %s    %s\n" % (row_count, row['id'])
        cursor.execute("UPDATE exports SET (status) = (true), WHERE id = row['id']")
        pass

con.close()

但是我收到以下错误: -

psycopg2.ProgrammingError: can't call .execute() on named cursors more than once

1 个答案:

答案 0 :(得分:0)

您需要一个新游标来执行UPDATE查询:

import psycopg2
import psycopg2.extras
import sys

query = """select * from exports;"""

con = psycopg2.connect("dbname='test' user='postgres' password='*****'")
cursor = con.cursor('server_side_cursor', cursor_factory=psycopg2.extras.DictCursor)
cursor.execute(query)

while True:
    rows = cursor.fetchmany(5000)
    if not rows:
        break
    row_count = 0
    for row in rows:
        row_count += 1
        print "row: %s    %s\n" % (row_count, row['id'])
        cursor2 = con.cursor()
        cursor2.execute("UPDATE exports SET (status) = (true), WHERE id = row['id']")
        cursor2.close()

con.close()