Problem with sqlite3 cursor and imbricated for loop

Michiel Overtoom motoom at xs4all.nl
Tue Nov 11 20:09:39 EST 2008


Charles V. wrote:

> It seems the second call to execute modify the first cursor. Is it normal ? 
> How am I suppose to write this ?

Maybe introduce a second cursor?

import sqlite3
conn = sqlite3.connect(':memory:')
c = conn.cursor()
d = conn.cursor() # second cursor
c.execute('''create table stocks
(date text, trans text, symbol text,
  qty real, price real)''')
c.execute("insert into stocks values ('2006-01-05','BUY','RHAT',100,35.14)")
c.execute("insert into stocks values ('2006-01-06','BUY','RHAT',100,20.0)")
c.execute("insert into stocks values ('2006-01-07','BUY','RHAT',100,15.0)")
c.execute("insert into stocks values ('2006-01-08','BUY','RHAT',100,10.0)")
conn.commit()
c.execute("select * from stocks")
for s in c:
    print s[0]
    d.execute("select * from stocks where price<20") # use the second cursor
    for s in d:
       print '  '+s[0]
c.close()


Outputs:

2006-01-05
   2006-01-07
   2006-01-08
2006-01-06
   2006-01-07
   2006-01-08
2006-01-07
   2006-01-07
   2006-01-08
2006-01-08
   2006-01-07
   2006-01-08


-- 
"The ability of the OSS process to collect and harness
the collective IQ of thousands of individuals across
the Internet is simply amazing." - Vinod Vallopillil
http://www.catb.org/~esr/halloween/halloween4.html



More information about the Python-list mailing list