psycopg2:在 SELECT 查询之间执行更新后,为 SELECT 查询的 RE-运行 重新使用游标

psycopg2: RE-USE of a cursor for a RE-RUN of a SELECT query after doing an UPDATE in between the SELECT queries

寻求以下使用 python 和 psycopg2 的最佳实践建议:

(1) Run a select query on "table01"
(2) Update "table01"
(3) Re-run the same select query on "table01"
conn01 = psycopg2.connect(host=DB_HOST, database=DB_NAME, user=DB_USER, password=DB_PASS)
cursor01 = conn01.cursor(cursor_factory=psycopg2.extras.DictCursor)

# (1) first select query
cursor01.execute("SELECT * FROM table01")
set01 = cursor01.fetchall()

# (2) some code in the middle that updates table01 

# (3A) re-run of the same select query
updated_set01 = cursor01.fetchall()

虽然我没有从非空表01中删除任何行,但(3A)的结果是空的。

将以下内容插入步骤 3 可得到所需的结果:

# (3B) re-run of the same select query
cursor01.execute("SELECT * FROM table01")
updated_set01 = cursor01.fetchall()

(3B) 重新使用 cursor01 是正确的程序吗?或者,我应该为 re-运行?

创建另一个游标吗?

谢谢。

https://www.psycopg.org/docs/cursor.html,我现在明白了运行 fetchall()清空游标。我现在将使用:

conn01 = psycopg2.connect(host=DB_HOST, database=DB_NAME, user=DB_USER, password=DB_PASS)
cursor01 = conn01.cursor(cursor_factory=psycopg2.extras.DictCursor)

# (1) first select query
cursor01.execute("SELECT * FROM table01")
set01 = cursor01.fetchall()

# (2) some code in the middle that updates table01 

# (3B) re-run of the same select query
cursor01.execute("SELECT * FROM table01")
updated_set01 = cursor01.fetchall()

谢谢@AdrianKlaver