2012-10-18 114 views
4
class MySQL(object): 

    def __init__(self): 
     self.dbpool = adbapi.ConnectionPool(
      'MySQLdb', 
      db='dummy', 
      user='root', 
      passwd='', 
      host = 'localhost', 
      cp_reconnect = True, 
      cursorclass=MySQLdb.cursors.DictCursor, 
      charset='utf8', 
      use_unicode=True 
     ) 

    def process(self, item): 
     query = self.dbpool.runInteraction(self.conditionalInsert, item).addErrback(self.handle_error)   
     return item 


    def conditionalInsert(self, tx, item): 
     tx.execute("INSERT INTO User (user_name) VALUES (%s)",(name)) 
     tx.execute("SELECT LAST_INSERT_ID()") 
     lastID = getID(tx.fetchone()) 
     # DO SOMETHING USING lasID 
     ... 
     ... 
    def handle_error(self, e): 
     log.err(e) 

我們下面第二行的lastID對應於插入第一行嗎?或者它可能來自任何runInteraction線程?扭曲的adbapi:runInteraction last_insert_id()

tx.execute("INSERT INTO User (user_name) VALUES (%s)",(name)) 
    tx.execute("SELECT LAST_INSERT_ID()") 

回答

1

最後一個id將是同一個事務中最後插入的行的id。

我測試使用下面的操作:

  1. 開始交易,並插入一行使用runInteraction(...)函數

  2. 得到最後插入的ID,例如它是18

  3. 睡眠30在功能秒,其中事務中運行

  4. 插入行到同一個表使用MySQL客戶端或phpMyAdmin的

  5. 得到從步驟4中,例如,最後插入ID它是19點

  6. 睡覺函數返回和查詢最後插入的ID再次使用同一個交易對象,最後插入的id還是18

+0

非常感謝你的反應。 已經3年多了,我發佈了這個,並已經想出了你說的話。我非常感謝你爲此提供答案。 :) –