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。
我已经使用以下操作对其进行了测试:
使用 runInteraction(...) 函数开始一个事务并插入一行
获取最后的插入 ID,例如18岁
在事务运行的函数中休眠 30 秒
使用 mysql 客户端或 phpMyAdmin 向同一个表插入一行
从第 4 步获取最后插入的 ID,例如19岁
休眠函数返回并查询最后一次插入的id再次使用相同的事务对象,最后一次插入的id仍然是18
关于python - 扭曲的 adbapi : runInteraction last_insert_id(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12953784/