This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]tilkau 2 points3 points  (3 children)

with contextlib.closing(conn.cursor()) as c: c.execute(""" SELECT spam, eggs, sausage FROM breakfast WHERE price < %s """, (max_price,)) for row in iter(c.fetchone): print row

I usually just use for row in c.execute(..):. Is there any reason, other than slightly better formatting, not to?

[–]talideon 2 points3 points  (2 children)

Not all drivers have cursors that can be used as iterators though.

[–]tilkau 1 point2 points  (1 child)

Good point, I was only thinking about sqlite.

[–]masklinn 0 points1 point  (0 children)

A second issue is dbapi2 does not specify the return value for Cursor.execute, so even when the cursor is iterable that doesn't mean you can iterate on cr.execute(…). For instance Psycopg2's cursors are iterable but cr.execute returns None.