2012-10-18 110 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年多了,我发布了这个,并已经想出了你说的话。我非常感谢你为此提供答案。 :) –