我从使用 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 网站的有用信息
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.
最佳答案
我认为你最后的陈述是错误的,因为 .fetchall()
返回一个新列表,其中包含游标查询返回的所有行,之后你可以重用游标。 (但在考虑重新使用新游标之前,我会测试新游标的成本是多少。)[好吧,我不知道这是不是真的,但它适用于 dbapi 兼容的 sqlite3 绑定(bind)]
关于python - pyodbc 游标重用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8916386/