扭曲的adbapi:runInteraction last_insert_id()

2024-10-01 00:24:09 发布

您现在位置: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 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线程?在

^{pr2}$

Tags: nameselftrueexecutedeferroriteminsert
1条回答
网友
1楼 · 发布于 2024-10-01 00:24:09

最后一个id将是同一事务中最后插入的行的id。在

我用以下操作测试它:

  1. 使用runInteraction(…)函数开始事务并插入行

  2. 获取最后一个插入id,例如它是18

  3. 在运行事务的函数中休眠30秒

  4. 使用mysql client或phpMyAdmin在同一个表中插入一行

  5. 从步骤4中获取最后一个insert id,例如它是19

  6. 休眠函数返回并查询最后一个insert id再次使用同一个事务对象,最后一个insert id仍然是18

相关问题 更多 >