首页 > 解决方案 > psycopg2:在 SELECT 查询之间执行 UPDATE 后,重新使用游标以重新运行 SELECT 查询

问题描述

寻求使用 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()

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

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

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

(3B) 重新使用 cursor01 是正确的程序吗?或者,我应该为重新运行创建另一个游标吗?

谢谢你。

标签: pythonpostgresqlpsycopg2

解决方案


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


推荐阅读