Rameen Rastan Rameen Rastan - 8 months ago 53
Python Question

Can I iterate over a cursor in pymssql more than once?

For example, if I run a sql query in python (using pymssql):

cursor.execute("""SELECT * FROM TABLE""")

Then I do:

for row in cursor:
print row[0]

but then I want to loop through the table a second time for a different operation, like this:

for row in cursor:
print row[1]

(Obviously I could do both of these in 1 loop, this is just for example's sake). Can I do this without re-executing the query again?


No, cursors in pymssql function like a generator. Once you get the results from them, they no longer contain the result set.

The only way to do this is to save the query results to an intermediary list.

For example:

import pymssql
database = pymssql.connect()
db_cursor = database.cursor()
db_cursor.execute("""SELECT * FROM Table""")
results = db_cursor.fetchall()
for result in results:
for result in results: