pyodbc 游标重用

发布于 2024-12-27 17:40:19 字数 742 浏览 0 评论 0原文

我从使用 pyodbc 连接到 SQL Server 的 python 代码对数据库进行多次查询。

cursor = connection.connect(connection_string)
qry1 = "Select * FROM Table1"

rows = cursor.execute(qry1).fetchall()

for row in rows:
   qry2 = "Select * FROM Table2"

   rows2 = cursor.execute(qry2).fetchall()

   for row2 in rows2:
      print row2

这有效并成功地完成了两个查询。

我怎样才能重用光标对象?

我想当我运行时,

rows2 = cursor.execute(qry2).fetchall()

rows和rows2现在会指向同一个东西(对象)。

编辑:来自 pyodbc 网站的有用信息

由于这会将所有行读取到内存中,因此如果行数很多,则不应使用它。请考虑迭代行。但是,它对于释放游标很有用,因此您可以在处理结果行之前执行第二个查询。

光标信息

I make multiple queries to my DB from my python code that uses pyodbc to connect to a SQL Server.

cursor = connection.connect(connection_string)
qry1 = "Select * FROM Table1"

rows = cursor.execute(qry1).fetchall()

for row in rows:
   qry2 = "Select * FROM Table2"

   rows2 = cursor.execute(qry2).fetchall()

   for row2 in rows2:
      print row2

This works and successfully goes through both queries to completion.

How is it that I can reuse the cursor object?

I would think when I ran

rows2 = cursor.execute(qry2).fetchall()

That rows and rows2 would now point to the same thing (object).

EDIT: Useful info from pyodbc site

Since this reads all rows into memory, it should not be used if there are a lot of rows. Consider iterating over the rows instead. However, it is useful for freeing up a Cursor so you can perform a second query before processing the resulting rows.

cursor info

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

抚你发端 2025-01-03 17:40:19

我认为您的最后一个语句是错误的,因为 .fetchall() 返回一个新列表,其中包含游标查询返回的所有行,之后您可以重用游标。 (但在考虑重用它们之前,我会测试新游标的成本。) [好吧,我不知道这是否属实,但它适用于 dbapi 兼容的 sqlite3 绑定]

I think your last statement is false, as .fetchall() returns a new list containing all the rows returned by the cursors query, after which you may reuse the cursor. (but i'd test what the cost of a new cursor is before thinking about reusing them.) [well, i don't know if this is really true but it is for the dbapi compatible sqlite3 bindings]

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文