Ask Your Question
3

How can the __iter__ method of the cursor class in psycopg2 be expanded?

asked 2022-08-03 11:00:00 +0000

devzero gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2021-06-30 06:00:00 +0000

bukephalos gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-08-03 11:00:00 +0000

Seen: 16 times

Last updated: Jun 30 '21