doutu1939 2017-06-28 08:05
浏览 46
已采纳

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

// update the CloseJira status into the database

Problem Statement - Golang how and where to call autogeneratedjiraclose() function to run some operation if rollback trigger.

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条回答 默认 最新

  • dongqinta4174 2017-06-28 09:18
    关注

    Here is pattern I use often when I need a transaction:

    func Foo() (err error) {
        var tx *sql.Tx
        tx, err = db.Begin()
        if err != nil {
            return err
        }
        defer func() {
            if err == nil {
                tx.Commit()
            } else {
                tx.Rollback()
            }
        }()
        // Do whatever you want here.
    }
    

    The trick is that here, the deferred function will always run at the end. If your function returns with an error, you can get it and rollback (and take whatever other action you want to), and if the function returns normally, you can commit the transaction.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么