Search code examples
pythonoracleoracle12c

Retrieving identity of most recent insert in Oracle DB 12c


I'd like to have returned to me (via cx_oracle in python) the value of the Identity that's created for a row that I'm inserting. I think I can figure out the python bit on my own, if someone could please state how to modify my SQL statement to get the ID of the newly-created row.

I have a table that's created with something like the following:

CREATE TABLE hypervisor
  (
    id NUMBER GENERATED BY DEFAULT AS IDENTITY (
    START WITH 1 NOCACHE ORDER ) NOT NULL ,
    name       VARCHAR2 (50)
  )
  LOGGING ;
ALTER TABLE hypervisor ADD CONSTRAINT hypervisor_PK PRIMARY KEY ( id ) ;

And I have SQL that's similar to the following:

insert into hypervisor ( name ) values ('my hypervisor')

Is there an easy way to obtain the id of the newly inserted row? I'm happy to modify my SQL statement to have it returned, if that's possible.

Most of the google hits on this issue were for version 11 and below, which don't support automatically-generated identity columns so hopefully someone here can help out.


Solution

  • Taking what user2502422 said above and adding the python bit:

    newest_id_wrapper = cursor.var(cx_Oracle.STRING)
    sql_params = { "newest_id_sql_param" : newest_id_wrapper }
    sql = "insert into hypervisor ( name ) values ('my hypervisor') " + \             
          "returning id into :python_var"
    cursor.execute(sql, sql_params)
    newest_id=newest_id_wrapper.getvalue()