【问题标题】:Twisted adbapi: runInteraction last_insert_id()扭曲的 adbapi:runInteraction last_insert_id()
【发布时间】:2012-10-18 11:40:53
【问题描述】:
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 线程?

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

【问题讨论】:

    标签: python mysql last-insert-id


    【解决方案1】:

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

    我已经使用以下操作对其进行了测试:

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

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

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

    4. 使用mysql客户端或phpMyAdmin在同一张表中插入一行

    5. 从第 4 步获取最后一个插入 ID,例如现在是 19 岁

    6. sleeping函数返回查询最后插入id再次使用同一个Transaction对象,最后插入id还是18

    【讨论】:

    • 非常感谢您的回复。自从我发布这篇文章并明白你所说的以来已经 3 年多了。我非常感谢您为此提供答案。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-22
    • 2010-10-15
    • 2011-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多