cx_Oracle: How do I iterate over a result set?
<p>There are several ways to iterate over a result set. What are the tradeoff of each?</p>

<p>The canonical way is to use the built-in cursor iterator.</p>

<pre><code>curs.execute('select * from people')
for row in curs:
    print row
</code></pre>

<hr>

<p>You can use <code>fetchall()</code> to get all rows at once.</p>

<pre><code>for row in curs.fetchall():
    print row
</code></pre>

<p>It can be convenient to use this to create a Python list containing the values returned:</p>

<pre><code>curs.execute('select first_name from people')
names = [row[0] for row in curs.fetchall()]
</code></pre>

<p>This can be useful for smaller result sets, but can have bad side effects if the result set is large.</p>

<ul>
<li><p>You have to wait for the entire result set to be returned to
your client process.</p></li>
<li><p>You may eat up a lot of memory in your client to hold
the built-up list.</p></li>
<li><p>It may take a while for Python to construct and deconstruct the
list which you are going to immediately discard anyways.</p></li>
</ul>

<hr>

<p>If you know there's a single row being returned in the result set you can call <code>fetchone()</code> to get the single row.</p>

<pre><code>curs.execute('select max(x) from t')
maxValue = curs.fetchone()[0]
</code></pre>

<hr>

<p>Finally, you can loop over the result set fetching one row at a time.  In general, there's no particular advantage in doing this over using the iterator.</p>

<pre><code>row = curs.fetchone()
while row:
    print row
    row = curs.fetchone()
</code></pre>
