GO的事务操作

代码:

package main

import (
    "database/sql"
    "fmt"

    _ "github.com/go-sql-driver/mysql"
)

//GO链接MySql
var Db *sql.DB //连接池对象

func initDB() (err error) {
    dsn := "username:password@tcp(127.0.0.1:3306)/database?charset=utf8"
    db, err := sql.Open("mysql", dsn)
    if err != nil {
        return err
    }
    err = db.Ping()
    if err != nil {
        return err
    }
    //设置数据库连接池最大连接数
    db.SetMaxOpenConns(10)
    //设置最大链接空闲数
    db.SetMaxIdleConns(5)
    Db = db
    return nil
}

type User struct {
    Id   int
    Name string
    Age  int
}

//查询
func query(where string) {
    sqlStr := "select Id,Name,Age from User " + where + ";"
    //执行
    rows, err := Db.Query(sqlStr)
    if err != nil {
        fmt.Printf("查询错误:%v\n", err)
        return
    }
    //释放连接
    defer rows.Close()
    for rows.Next() {
        var u User
        //赋值并关闭链接(Scan方法)
        err := rows.Scan(&u.Id, &u.Name, &u.Age)
        if err != nil {
            fmt.Println("查询循环错误")
            continue
        }
        fmt.Printf("Id:%v;Name:%v;Age:%v;\n", u.Id, u.Name, u.Age)
    }
}

func transactionDemo() {
    //开启十五
    tx, err := Db.Begin()
    if err != nil {
        if tx != nil {
            //回滚
            tx.Rollback()
        }
        fmt.Printf("开启事务失败,错误:%v\n", err)
        return
    }
    sqlStr1 := "Update User Set age = 100 where Id=?"
    _, err = tx.Exec(sqlStr1, 3)
    if err != nil {
        tx.Rollback()
        fmt.Printf("执行sqlStr1失败,错误:%v\n", err)
        return
    }
    sqlStr2 := "Update User Set age = 150 where Id=?"
    _, err = tx.Exec(sqlStr2, 4)
    if err != nil {
        tx.Rollback()
        fmt.Printf("执行sqlStr2失败,错误:%v\n", err)
        return
    }
    //提交事务
    err = tx.Commit()
    if err != nil {
        tx.Rollback()
        fmt.Printf("提交失败,错误:%v\n", err)
        return
    }
    fmt.Println("事务执行成功")
}

func main() {
    err := initDB()
    if err != nil {
        fmt.Printf("初始化失败,错误%v\n", err)
        return
    }
    fmt.Println("数据库链接成功。")
    fmt.Println("-----------------------------------")
    query("where id > 0")
    transactionDemo()
    fmt.Println("-----------------------------------")
    query("where id > 0")

}

结果:

 

 

参考:https://www.bilibili.com/video/BV1fz4y1m7Pm?p=137

 

posted @ 2021-07-02 15:26  蜗牛的礼物  阅读(1082)  评论(0编辑  收藏  举报