在mysql中,可用begin, commit/rollback命令来操作,下面来看go代码操作:
- package main
-
- import (
- "fmt"
- "database/sql"
- _ "github.com/go-sql-driver/mysql"
- )
-
- func main() {
- db, _ := sql.Open("mysql", "root@/taoge")
- tx, _ := db.Begin() // begin transaction
-
- var aff1, aff2 int64 = 0, 0
- result1, _ := tx.Exec("UPDATE user SET strValue='3041' WHERE strKey=?", "k1")
- result2, _ := tx.Exec("UPDATE user SET strValue='4041' WHERE strKey=?", "k2")
-
- if result1 != nil {
- aff1, _ = result1.RowsAffected()
- }
- if result2 != nil {
- aff2, _ = result2.RowsAffected();
- }
-
- fmt.Println(aff1)
- fmt.Println(aff2)
-
- if aff1 == 1 && aff2 == 1 {
- tx.Commit() // commit transaction
- fmt.Println("ok")
- } else {
- tx.Rollback() // rollback transaction
- fmt.Println("failed, then rollback")
- }
- }
自测OK. 可以玩一下, 对理解mysql事务有帮助。
没什么好说的。