python – 扭曲的adbapi:runInteraction last_insert_id()
发布时间:2020-12-20 13:30:41  所属栏目:Python  来源:网络整理 
            导读: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 pr
                
                
                
            | 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对应于第一行中的insert?或者它可以来自任何runInteraction线程? tx.execute("INSERT INTO User (user_name) VALUES (%s)",(name))
    tx.execute("SELECT LAST_INSERT_ID()")解决方法
 最后一个id将是同一事务中最后一个插入行的id. 
  
  我测试它使用以下操作: >开始一个事务并使用runInteraction(…)函数插入一行>获取最后一个插入ID,例如现在是18岁>在事务运行的函数中休眠30秒>使用mysql客户端或phpMyAdmin向同一个表插入一行>从步骤4获取最后一个插入ID,例如现在是19岁> sleep函数返回并查询最后一次插入id再次使用相同的Transaction对象,最后一次插入id仍为18 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! | 
