31

Go 语言操作 MySQL 之 事务操作

 3 years ago
source link: https://studygolang.com/articles/29656
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

友情提示:此篇文章大约需要阅读 5分钟 9秒,不足之处请多指教,感谢你的阅读。 订阅本站

事务

数据库事务( transaction )是访问并可能操作各种数据项的一个数据库操作序列,这些操作要么全部执行,要么全部不执行,是一个不可分割的工作单位。 事务由事务开始与事务结束之间执行的全部数据库操作组成。

MySQL 存储引擎分类有 MyISAM、InnoDB、Memory、Merge等,但是其中最为常用的就是 MyISAM 和 InnoDB 两个引擎,这两个引擎中,支持事务的引擎就是 Innodb(MySQL 默认引擎),在创建数据库中要注意对应引擎。

这里可以看一下针对 MySQL 选择引擎的文章:

怎么优雅的选择 MySQL 存储引擎 - Debug客栈

事务 ACID

通常事务必须满足4个条件( ACID ):原子性(Atomicity,或称不可分割性)、一致性(Consistency)、隔离性(Isolation,又称独立性)、持久性(Durability)。

YriUBba.png!web

Go 操作 MySQL 使用事务

Go语言中使用以下三个方法实现MySQL中的事务操作:

// 开始事务
func (db *DB) Begin() (*Tx, error)
// 回滚事务
func (tx *Tx) Rollback() error
// 提交事务
func (tx *Tx) Commit() error

示例代码:

// 事务更新操作
func transActionUpdate() {
    tx, err := db.Begin()
    if err != nil {
        if tx != nil {
            _ = tx.Rollback()
        }
        fmt.Printf("begin trans action failed, err:%v\n", err)
        return
    }
    sqlStr1 := "UPDATE user SET age = ? WHERE id = ?"
    result1, err := tx.Exec(sqlStr1, 20, 1)
    if err != nil {
        _ = tx.Rollback()
        fmt.Printf("exec failed, err:%v\n", err)
        return
    }
    n1, err := result1.RowsAffected()
    if err != nil {
        _ = tx.Rollback()
        fmt.Printf("exec result1.RowsAffected() failed, err:%v\n", err)
        return
    }
    sqlStr2 := "UPDATE user SET age = ? WHERE id = ?"
    result2, err := tx.Exec(sqlStr2, 20, 6)
    if err != nil {
        _ = tx.Rollback()
        fmt.Printf("exec failed, err:%v\n", err)
        return
    }
    n2, err := result2.RowsAffected()
    if err != nil {
        _ = tx.Rollback()
        fmt.Printf("exec result1.RowsAffected() failed, err:%v\n", err)
        return
    }

    if n1 == 1 && n2 == 1 {
        _ = tx.Commit()
        fmt.Printf("transaction commit success\n")
    } else {
        _ = tx.Rollback()
        fmt.Printf("transaction commit error, rollback\n")
        return
    }
}

参考(学习)文章: Go语言操作MySQL – 李文周的个人博客

欢迎关注我们的微信公众号,每天学习Go知识

FveQFjN.jpg!web

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK