python - 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 是正确的程序吗?或者,我应该为重新运行创建另一个游标吗?
谢谢你。
解决方案
从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
推荐阅读
- swift - 在 Swift 中解码/解析 CSV 和类似 CSV 的文件
- xml - 如何将xml输入(请求)传递给.net core 3.1上的Web api
- python - 如何将 LMFit 参数限制为仅负值?
- amazon-web-services - 如何理解 S3 或 Cassandra 中的 OLAP 多维数据集?
- javascript - 在 express 服务器上提供 create-react-app 构建文件
- javascript - 从本地存储中删除仅选定的列表项 - 纯 JS
- django - 想要显示详细视图,单击列表视图中的链接
- vb.net - 在 windows 中生成声音频率 - VB.Net
- sql - 如何插入具有 ADT 类型属性的数据库表中?使用 Oracle Live SQL
- python - 你如何在python中更改变量函数参数