Python MySql rowIds

In SQL, a particular row is represented by an insertion id which is known as row id. We can get the last inserted row id by using the attribute lastrowid of the cursor object.

MySql rowIds example:

In the following example we will fetch the rowid of last inserted row

CopiedCopy Code

import mysql.connector  
myconn = mysql.connector.connect(host = "localhost", user = "root",password = "naveen",database = "PythonDB")  
cur = myconn.cursor()  
      
sql = "insert into Employee(name, id, salary, dept_id, branch_name) values (--s, --s, --s, --s, --s)"  
val = ("Mike",105,28000,202,"Guyana")  
      
try:  
    cur.execute(sql,val)  
    myconn.commit()  
    print(cur.rowcount,"record inserted! id:",cur.lastrowid)  
  
except:  
    myconn.rollback()  
  
myconn.close()