python - pyodbc 游标重用

标签 python sql-server-2008-r2 pyodbc

我从使用 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()

rowsrows2 现在将指向同一事物(对象)。

编辑:pyodbc 网站的有用信息

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

最佳答案

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

关于python - pyodbc 游标重用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8916386/

相关文章:

sql - 如何在sql server management studio中查找linked_server名称?

sql-server - 如何在 SQL Server 的表值函数中使用 CTE 语句

database - 如何创建对 Sage ERP 数据库具有只读访问权限的帐户以与 pyodbc 一起使用

python - 为什么 Pexpect 在执行某些命令后间歇性挂起(未检测到 EOF)?

python - 根据旧数据帧中重新格式化的列创建新数据帧

sql-server-2008-r2 - SQL Server 尝试访问使用 dbo "Invalid object name ' dbo.Function_Client 创建的 udf 函数时。”

python - 无法将 NULL 插入列 'Type'

python - pyodbc 到 SQL Server 获取结果时太慢

python - DRF3 在 m2m 关系上创建嵌套序列化器

python - 使用 Django-storages 删除 Amazon S3 中的文件