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
sleep函数返回并再次使用相同的Transaction对象查询最后的插入id,最后的插入id仍然是18
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)