Re: Iterating through cur and cur.fetchone() - Mailing list psycopg

From Daniele Varrazzo
Subject Re: Iterating through cur and cur.fetchone()
Date
Msg-id CA+mi_8aWGEwB-xxQY1nKm-YL3z6BgSZnGo76rgZ5uzybXSW4oQ@mail.gmail.com
Whole thread Raw
In response to Iterating through cur and cur.fetchone()  (Håvard Wahl Kongsgård <haavard.kongsgaard@gmail.com>)
List psycopg
2011/10/10 Håvard Wahl Kongsgård <haavard.kongsgaard@gmail.com>:
> Hi, how do I use cur.fetchone() when iterating through a cur object.
>
> with
> conn = psycopg2.connect()
> cur = conn.cursor()
> SQL = ('select * from something limit 1000')
>
> n = 1
> cur.execute(SQL)
> for edge_list in cur:
>    edge = cur.fetchone()
>    print n
>
>    n = n +1
>
> I get
> n = 500
>
> when I skip edge = cur.fetchone()
>
> for edge_list in cur:
>    print n
>
>    n = n +1
>
> n = 1000
>
> Why does this happen, and what is the solution?

You are consuming the cursor both with the iteration and with the
fetchone. You should either use:

    for record in cur:
        # use record

or

    while 1:
        record = cur.fetchone()
        if not record: break
        # use record

Not mix the two together.

-- Daniele

psycopg by date:

Previous
From: Håvard Wahl Kongsgård
Date:
Subject: Iterating through cur and cur.fetchone()
Next
From: Håvard Wahl Kongsgård
Date:
Subject: Re: Iterating through cur and cur.fetchone()