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:
print(result[0])
for result in results:
print(result[1])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With