Announcement Announcement Module
Collapse
No announcement yet.
how to get the last inserted ID from the most recent INSERT Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • how to get the last inserted ID from the most recent INSERT

    Hi,

    Does any one know how to get the last inserted ID from the most recent INSERT on an AUTO_INCREMENT field through spring-python?

    For example, lets suppose that I've defined pets.id as AUTO_INCREMENT below, if I have:

    Code:
        def addPet(self, owner_id, name, birthDate, type):
            """Store a new pet in the database."""
            rowsAffected = self.database_template.execute("""
                    INSERT INTO pets
                    (id, name, birth_date, type_id, owner_id)
                    values
                    (null, ?, ?, ?, ?)
                """, ( name, birthDate, type, owner_id))
            return rowsAffected
    How could I get the id of the most recent insert into the pets table?
    Can the database_template return the id, instead of the rows affected?
    Do I need to create another mysql query and make another trip to the db to find out which is the latest pets.id value?
    Please let me know, I am looking forward to hearing news from you. Thank you very much in advance.

  • #2
    Doing a little digging, I found http://www.mikusa.com/python-mysql-docs/query.html showing how to get the value if you were using MySQL directly from Python's database API. It requires access to the cursor. Since the cursor has been abstracted away, we would have to entertain the idea of changing DatabaseTemplate's API in order to get it.

    Until that kind of change happens, your other option is to run another query.

    Most of the time, I'm working with Oracle, so another option is to fetch the new key value before running the insert. This depends on the database having accessible counters. I don't know if MySQL counters provide the same convenience.

    Comment

    Working...
    X