idiom for inserting multiple rows with auto-increment IDs
"Daniel Lenski" <[email protected]>
| Newsgroups | gmane.comp.python.db.pysqlite.user |
|---|---|
| Message-ID | <[email protected]> |
Hi all,
I'm new to pysqlite, and trying to figure out the most efficient an
appropriate way to insert multiple rows into a table with auto-increment
IDs, while also saving those new IDs.
newitems = [ list of new items ]
for row in newitems:
cur.execute("insert into table (id,column1,column2,column3) values
(NULL,?,?,?)",
(row.column1, row.column2, row.column3))
row.id = cur.lastrowid
This seems pretty awkward though... I have also tried this:
from itertools import izip, count
newitems = [ list of new items ]
max, = con.execute("select max(id)+1 from table")
start = max[0] or 0
con.executemany("insert into table (id,column1,column2,column3) values
(NULL,?,?,?)",
izip(count(start), (x.column1 for x in newitems),
(x.column2for x in newitems, (
x.column3 for x in newitems)))
for id,row in enumerate(newitems):
row.id = id+start
This is also darn ugly, though I feel that it's kind of "more pythonic" in
its use of iterators. I guess I'm wondering, is there a better way? Is
there a way to insert a whole bunch of items and then get the auto-increment
IDs for all of them in one fell swoop?
Thanks!
Dan Lenski
_______________________________________________
pysqlite mailing list
pysqlite-IAPFreCvJWPBWskQ1e/[email protected]
http://lists.initd.org/mailman/listinfo/pysqlite