Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 310
Rameen Rastan Avatar asked Aug 09 '16 13:08

Rameen Rastan


1 Answers

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:
    print(result[0])
for result in results:
    print(result[1])
like image 77
Morgan Thrapp Avatar answered Oct 31 '22 19:10

Morgan Thrapp