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()
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为您的最后一个语句是错误的,因为
.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]