On Jun 7, 2011, at 6:03 AM, Felix Wolfsteller wrote:

> Hi,
> 
> I try to insert a big number of of rows to a table and want to receive the 
> ids 
> that were assigned to these (new) rows.
> If i insert a single row, it works as expected, but with multiple rows I run 
> into an error:
> AttributeError: 'DefaultExecutionContext' object has no 
> attribute '_inserted_primary_key' .
> 
> I use SQLAlchemy 0.6.3-3 (Debian Squeeze) with an sqlite database.
> 
> Pseudo code follows.
> Is there another obvious way to retrieve the ids?

This is a limitation of the DBAPI that none of the various methods we use to 
get "last inserted id" are available with an executemany(), i.e. .lastrowid, 
result sets for RETURNING, etc.    So you can either establish the PK 
identities beforehand, use individual executions, or in some cases use a 
heuristic to guess (i.e. 20 new rows would be Ids 43 through 63 type of thing, 
just watch concurrency with that approach).


> 
> Enjoy,
> --felix
> 
> 
> #
> # Setup Session etc.
> #
> 
> data_table = Table('data', metadata,
>                   Column('id', Integer, primary_key=True),
>                   Column('stuff', String, nullable=False) )
> 
> insert_dicts = []
> for x in range(10):
>    insert_dicts.append(dict(stuff=str(x)))
> 
> stmt = data_table.insert(bind=Session.bind)
> res = stmt.execute(insert_dicts)
> 
> # Correct:
> print res.rowcount
> 
> print r.inserted_primary_key()
> # Raises:
> #AttributeError: 'DefaultExecutionContext' object has no 
> #attribute '_inserted_primary_key'
> 
> # Initial trial with r.last_inserted_ids()
> #SADeprecationWarning: Use inserted_primary_key
> #Error - <type 'exceptions.AttributeError'>: 'DefaultExecutionContext' object 
> #has no attribute '_inserted_primary_key'
> 
> 
> 
> -- 
> Felix Wolfsteller |  ++49 541 335083-783  |  http://www.intevation.de/
> PGP Key: 39DE0100
> Intevation GmbH, Neuer Graben 17, 49074 Osnabrück | AG Osnabrück, HR B 18998
> Geschäftsführer: Frank Koormann, Bernhard Reiter, Dr. Jan-Oliver Wagner
> 
> -- 
> You received this message because you are subscribed to the Google Groups 
> "sqlalchemy" group.
> To post to this group, send email to sqlalchemy@googlegroups.com.
> To unsubscribe from this group, send email to 
> sqlalchemy+unsubscr...@googlegroups.com.
> For more options, visit this group at 
> http://groups.google.com/group/sqlalchemy?hl=en.
> 

-- 
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To post to this group, send email to sqlalchemy@googlegroups.com.
To unsubscribe from this group, send email to 
sqlalchemy+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en.

Reply via email to