Search code examples
mysqlpython-3.xcursorpymysql

pymysql3 cursor.lastrowid doesn't work sometimes


I have a strange problem with pymysql3 cursor.lastrowid property. I'm writing a threaded python3 application. It has an opened pymysql3 connector in a main thread, and a lot of functions that can do select/insert/update in a random way. I run these functions in application's threads. Every function has the next construction:

def function...(link_to_connector) 
  .... 
  cur = link_to_connector.cursor(pymysql.cursors.DictCursor) 
  cur.execute(...) 
  id = cur.lastrowid #Used only in INSERT constructions
  cur.close() 
  ...

The connector was opened in the next way:

self.connector = pymysql.connect(host, user, pass, db, charset='utf8')
self.connector.autocommit(True)    

All works properly, but sometimes cur.lastrowid equals 0 after a fresh insert operation. A real inserted row in a DB has non-zero id. The DB is MySQL with InnoDB tables.

Could anyone help me,

  1. What is going wrong in this case?

  2. Is it a good method to open and to close the cursor in every function?


Solution

  • I have solved this problem. Is was a typical race condition, because a pymysql.connector() object is not a thread-safe thing.