Search code examples
pythonmysqlmysql-connectormysql-connector-python

stored procedure get last inserted row python mysql connector


I am inserting data via a store procedure and I am trying to get the last id inserted. Data is being inserted. But when I try to return the last ID I get none or 0. I set the id field manually because of data replication. Not sure what I am missing.

 query='database.insert_data'
 params ='Josh'
 last_id = mysql_conn.insert_proc(query, params)
 print(last_id.fetchone())
 prints none


 class to insert data
 def insert_proc(self,query,params):
    self.curr.callproc(query, params)
    self.conn.commit()
    return self.curr

 stored procedure      
 CREATE DEFINER=`me`@`localhost` PROCEDURE `insert_data`(v_name varchar(10))
 SET @max_id = (select max(id)+1 from table);

    insert into table (id,name)values(@max_id,v_name);

    select @max_id;

Solution

  • I'm not very familiar with Python but according to the MySQL documentation here:

    Result sets produced by the stored procedure are automatically fetched and stored as MySQLCursorBuffered instances. For more information about using these result sets, see stored_results().

    "see stored_results()" leads to code examples featuring iteration over cursor.stored_results().