1 | initial version |
The __iter__
method of the cursor class in psycopg2 can be expanded by using a generator function that yields each row of the result set. Here is an example code:
import psycopg2
con = psycopg2.connect(database="mydb", user="myuser", password="mypassword")
cur = con.cursor()
def iter_rows(cursor):
while True:
row = cursor.fetchone()
if not row:
break
yield row
cur.execute("SELECT * FROM mytable")
for row in iter_rows(cur):
print(row)
cur.close()
con.close()
In this code, we define a generator function iter_rows
that takes a cursor as an argument. The function uses a while loop to fetch each row from the cursor and yield it. The loop exits when there are no more rows to fetch. We then pass our cursor to iter_rows
and iterate over the rows using a for loop. Finally, we close the cursor and connection to the database.