4
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)

下の 2 行目の lastID は、1 行目の挿入に対応しますか? または、runInteraction スレッドのいずれかからのものである可能性がありますか?

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

1 に答える 1

1

最後の ID は、同じトランザクションで最後に挿入された行の ID になります。

次の操作を使用してテストしました。

  1. トランザクションを開始して行を挿入するには、runInteraction(...) 関数を使用します

  2. 最後の挿入 ID を取得します。たとえば、18 です。

  3. トランザクションが実行される関数で 30 秒間スリープする

  4. 同じテーブルに行を挿入するには、mysql クライアントまたは phpMyAdmin を使用します

  5. ステップ 4 から最後の挿入 ID を取得します。たとえば、19 です。

  6. スリープ状態の関数が返され、最後の挿入 ID を照会すると、同じトランザクション オブジェクトが再度使用されます。最後の挿入 ID は 18 のままです。

于 2016-02-27T08:57:36.977 に答える