Python MySQLdb equivalent for PHP’s mysql_insert_id()

What you’re looking for is lastrowid property of a cursor object.


import MySQLdb # MySQLdb module must be installed on the system
connection = MySQLdb.connect(...) # Details skipped
cursor = connection.cursor()
query = "INSERT INTO ... " # put query here
print cursor.lastrowid # BINGO! This will print the id (auto-increment column) of the last inserted row
# Other codes here

Thanks to this article on the Internet