Cursors in a Loop

t_rectenwald t.rectenwald at gmail.com
Thu Jan 3 19:47:27 EST 2008


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




More information about the Python-list mailing list