This repository has been archived on 2022-04-14. You can view files and clone it, but cannot push or open issues or pull requests.
manual-en-US/chapter-10
2020-03-27 14:29:41 +08:00
..
README.md Update documents 2020-03-27 14:29:41 +08:00

Transaction

If you want to begin a transaction, you have to create a session with engine.NewSession() at first, and then start session.Begin() and don't forget invoke session.Commit() after all operations finished.

Don't forget invoke session.Close().

session := engine.NewSession()
defer session.Close()

// add Begin() before any action
err := session.Begin()
user1 := Userinfo{Username: "xiaoxiao", Departname: "dev", Alias: "lunny", Created: time.Now()}
_, err = session.Insert(&user1)
if err != nil {
    session.Rollback()
    return
}
user2 := Userinfo{Username: "yyy"}
_, err = session.Where("id = ?", 2).Update(&user2)
if err != nil {
    session.Rollback()
    return
}

_, err = session.Exec("delete from userinfo where username = ?", user2.Username)
if err != nil {
    session.Rollback()
    return
}

// add Commit() after all actions
err = session.Commit()
if err != nil {
    return
}