python - 扭曲的 adbapi : runInteraction last_insert_id()

标签 python mysql last-insert-id

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()")

最佳答案

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

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

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

  2. 获取最后的插入 ID,例如18岁

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

  4. 使用 mysql 客户端或 phpMyAdmin 向同一个表插入一行

  5. 从第 4 步获取最后插入的 ID,例如19岁

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

关于python - 扭曲的 adbapi : runInteraction last_insert_id(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12953784/

相关文章:

php - LAST_INSERT_ID 在 UPDATE 上不起作用

python - 从python字典中删除重复的键但连接重复键的值

Python 将 r 放在 unicode 字符串变量之前

PHP 5.6,Unix 上的 PDO MySql 连接 (LAMPP) - fatal error : SQLSTATE[HY000] [1045]

mysql - 如何在将一个数据库与另一个数据库合并时解决主键冲突

php - 将日期格式化为人类可读的格式

mysql - 如何使用nifi在mysql中获取最后插入的记录

python - 使用 Python 返回 7 张扑克牌中包含一对的最佳牌 5 张

OpenShift API 的 Python 客户端并进行 oc 登录

mysql - Powershell 中的 last_insert_id