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.

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

报告相同问题?

悬赏问题

  • ¥100 求数学坐标画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站