如何在事务回滚上添加一些操作

时间:2017-06-28 08:05:21

标签: go

//将CloseJira状态更新到数据库

问题陈述 - Golang如何以及在何处调用autogeneratedjiraclose()函数,以便在回滚触发时运行某些操作。

func CloseJira(qMonName string) {
tx, err := dbCon.Begin()
notifier.CheckErr(err, "CloseJira() -> tx -> dbCon.Begin()", dbErrLog)
defer tx.Rollback()

stmt, errDBPrepare := tx.Prepare("update TABLE1 set 
Key=NULL, StatusKey='Closed', Statustime_UTC=? where Name=?") 
//Update db table record
notifier.CheckErr(errDBPrepare, "updateCloseJira() -> dbCon.Prepare()", 
dbErrLog)
defer stmt.Close() // danger!

res, errStmtExec := stmt.Exec(time.Now().UTC(), qMonName)
notifier.CheckErr(errStmtExec, "CloseJira() -> stmt.Exec()", dbErrLog)

err = tx.Commit()
notifier.CheckErr(err, "CloseJira() -> err -> tx.Commit()", dbErrLog)

_, errRowAffected := res.RowsAffected()
notifier.CheckErr(errRowAffected, "CloseJira() -> res.RowsAffected()", 
dbErrLog)
}

1 个答案:

答案 0 :(得分:0)

这是我在需要交易时经常使用的模式:

RewriteRule

诀窍在于,延迟函数将始终在最后运行。如果你的函数返回错误,你可以得到它并回滚(并采取你想要的任何其他动作),如果函数正常返回,你可以提交事务。

相关问题