Cursors in a Loop

t_rectenwald t.rectenwald at gmail.com
Fri Jan 4 02:25:18 CET 2008


On Jan 3, 7:47 pm, t_rectenwald <t.rectenw... at gmail.com> wrote:
> I have a python script that uses the cx_Oracle module.  I have a list
> of values that I iterate through via a for loop and then insert into
> the database.  This works okay, but I'm not sure whether I can use one
> cursor for all inserts, and define it outside of the loop, or
> instantiate and close the cursor within the loop itself.  For example,
> I have:
>
> for i in hostlist:
>     cursor = connection.cursor()
>     sql= "insert into as_siebel_hosts_temp values('%s')" % (i)
>     cursor.execute(sql)
>     cursor.close()
>
> And I've also tried:
>
> cursor = connection.cursor()
> for i in hostlist:
>     sql= "insert into as_siebel_hosts_temp values('%s')" % (i)
>     cursor.execute(sql)
> cursor.close()
>
> Both work fine, and execute in the same amount of time.  I'm just
> trying to understand what is the "correct" approach to use.
>
> Thanks,
> Tom

I think I have this one figured out.  The answer would be the second
option, i.e. keep the cursor instantion and close outside of the
loop.  I wasn't aware that one cursor could be used for multiple
executes.

Regards,
Tom



More information about the Python-list mailing list