How to return the last primary key after INSERT in pymysql (python3.5)?

xaero picture xaero · May 30, 2016 · Viewed 7.8k times · Source
CREATE TABLE `users` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `email` varchar(255) COLLATE utf8_bin NOT NULL,
    `password` varchar(255) COLLATE utf8_bin NOT NULL,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin
AUTO_INCREMENT=1 ;

for example, how to get the primary key id of the last record that I insert into the table by cursor.execute("insert into ...", ...)?

Answer

shivsn picture shivsn · May 30, 2016

after inserting,You can get it as: cursor.execute('select LAST_INSERT_ID()') or use cursor.lastrowid