Search code examples
pythonmysqlmariadbmysql-connector-python

How do I get generated uuid of last insert in python?


How do i get the generated uuid_short of my last insert in python?

cursor.lastrowid as recommended by here always returns 0

Here is my code

import mysql.connector as DB
addlink = "INSERT INTO links (i,action,client,file) values (uuid_short(),%s,%s,%s)"
cursor.execute(addlink,link)
print(cursor.lastrowid)

Solution

  • cursor.lastrowid returns the value generated for an AUTO_INCREMENT column by the previous INSERT statement. It can't be used if you generate an id by other means.

    You could first make a query to generate a UUID, then do an INSERT, e.g.:

    cursor.execute('SELECT UUID_SHORT()')
    uuid, = cursor.fetchone()
    cursor.execute(addlink, (uuid, *other_params))