[Tutor] insert queries into related tables referencing foreign keys using python
Monte Milanuk
memilanuk at gmail.com
Sat Dec 24 15:57:56 CET 2011
Lie Ryan <lie.1296 <at> gmail.com> writes:
> In python-sqlite, the rowid of the
> last insert operation can be queried using cursor.lastrowid. Therefore,
> you can query the lastrowid, right after the insert, to find the primary
> key of the value you had just inserted. So, in code:
>
> ...
> cur = conn.execute('INSERT ... ')
> pk = cur.lastrowid
> ...
>
> or even:
>
> ...
> pk = conn.execute('INSERT ... ').lastrowid
> ...
>
> Be careful that in multithreaded program, each thread should have their
> own cursors, or otherwise another thread could possibly do another
> insert before you can query the lastrowid.
>
okay, this touches on something that had been worrying me a bit... whether
another insert could hit before I queried for the lastrowid, regardless of how I
did it. So you're saying that as long as I have the one cursor open, the
lastrowid it gets will be the lastrowid from its operations, regardless of other
commits or transactions that may have happened in the meantime?
>
> In general, despite the superficial similarities, most database engine
> wrappers have their own ways of doing stuffs. Generally, you need a
> full-blown ORM to smooth out the differences.
>
So... what would be considered a 'full-blown' ORM? SQLobject or SQLalchemy...
or something else?
Thanks,
Monte
More information about the Tutor
mailing list