Tyler DeWitt
Tyler DeWitt

Reputation: 23576

pyodbc Cursor Reuse

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

Upvotes: 3

Views: 7878

Answers (1)

Dan D.
Dan D.

Reputation: 74685

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]

Upvotes: 3

Related Questions