扭曲的adbapi:runInteraction last_insert_id() [英] Twisted adbapi: runInteraction 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线程?
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()")
推荐答案
最后一个ID将是同一事务中最后插入的行的ID.
The last id will be the last inserted row's id in the same transaction.
我已经通过以下操作对其进行了测试:
I have test it use the following operations:
-
开始事务并使用runInteraction(...)函数插入一行
begin a transaction and insert a row use the runInteraction(...) function
获取最后一个插入ID,例如是18
get the last insert id, e.g. it is 18
在运行交易的功能中睡眠30秒
sleep 30 seconds in the function where transaction runs
使用mysql客户端或phpMyAdmin将一行插入同一表
insert a row to the same table use mysql client or phpMyAdmin
获取步骤4中的最后一个插入ID,例如是19
get the last insert id from step 4, e.g. it is 19
sleeping函数返回并再次使用同一Transaction对象查询最后一个插入ID,最后一个插入ID仍为18
sleeping function returns and query the last insert id use the same Transaction object again, the last insert id is still 18
这篇关于扭曲的adbapi:runInteraction last_insert_id()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!