Twisted adbapi: runInteraction last_insert_id()

空扰寡人 提交于 2019-12-10 17:19:16

问题


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)

The lastID we the second line below corresponds to insert in the first line ? or it could be from any of the runInteraction threads ?

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

回答1:


The last id will be the last inserted row's id in the same transaction.

I have test it use the following operations:

  1. begin a transaction and insert a row use the runInteraction(...) function

  2. get the last insert id, e.g. it is 18

  3. sleep 30 seconds in the function where transaction runs

  4. insert a row to the same table use mysql client or phpMyAdmin

  5. get the last insert id from step 4, e.g. it is 19

  6. sleeping function returns and query the last insert id use the same Transaction object again, the last insert id is still 18



来源:https://stackoverflow.com/questions/12953784/twisted-adbapi-runinteraction-last-insert-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!