用异常-捕获的方法,封装 insert, update, select, 传输错误或不达到期望结果(影响行数,或者返回结果集合行数),则直接抛出异常,异常由xpcall捕获,统一处理。
local function test_transaction(db)
transaction_start(db)
local affected_rows = insert_or_update(db, stmt1, expected_affected_rows)
local affected_rows = insert_or_update(db, stmt2, expected_affected_rows)
local res = select(db, stmt3, expected_rows)
if res[1].code == "test" then
local affected_rows = insert_or_update(db, stmt4, expected_affected_rows)
else
local affected_rows = insert_or_update(db, stmt5, expected_affected_rows)
end
transaction_commit(db)
end
local function test_transaction_handler(db, exitcode)
根据exitcode处理(回滚,断开链接或者别的)
end
local ok, err = xpcall(test_transaction, test_transaction_handler, db)
xiaojie liu於 2016年12月18日星期日 UTC+8下午5時09分14秒寫道:
最近业务中,需要显示使用事务的场景比较多。但是代码写出来,
个人觉得比较繁琐,下面是一段伪代码示例:--获取链接并开启事务
local ok, connection = mysql:open_and_begin()
if not ok then
return json.fail(msg)
end
-- 更新第一张表。
local dao01 = table01:new(connection)
local ok, effects = dao01:update(updates)
if not ok then
mysql:rollback_and_close(connection)
return json.fail(msg)
end
-- 更新第二张表。
local dao02 = table02:new(connection)
local del_ok, del_effects = dao02:update(updates)
if not del_ok then
mysql:rollback_and_close(connection)
return json.fail(msg)
end
--提交事务,并释放链接
tx_ok, tx_err = mysql:commit_and_close(connection)
if not tx_ok then
mysql:rollback_and_close(connection)
return json.fail(msg)
end
可以看到每个出错分支都要主动回滚及释放链接, 我想问的是,有没有什么方法或设计模式能避免这种情形,或者有什么自动回滚,提交及自动释放的机制?
有更简洁的模式的同学,请贴示例代码赐教。