package main import ( "database/sql" _ "github.com/go-sql-driver/mysql" "log" ) var Db *sql.DB func initdb() (err error) { Db, err = sql.Open("mysql", "root:123456@tcp(43.143.245.135:3306)/user") if err != nil { log.Println(err) return err } err = Db.Ping() if err != nil { log.Println(err) return err } log.Println("Successfully connected to mysql") Db.SetMaxOpenConns(10) Db.SetMaxIdleConns(5) return nil } func main() { err := initdb() if err != nil { return } transaction() } func transaction() { //开启事务 tx, err := Db.Begin() if err != nil { log.Println("begin failed", err) return } //执行多个sql操作,即一个事务 sqlstr1 := `update user set age=age-1 where id=1` sqlstr2 := `update user set age=age+1 where id=2` _, err = tx.Exec(sqlstr1) if err != nil { log.Println("执行sql1出错了,要回滚", err) //回滚操作 tx.Rollback() return } _, err = tx.Exec(sqlstr2) if err != nil { log.Println("执行sql2出错了,要回滚", err) //回滚操作 tx.Rollback() return } //上两步操作都执行成功,就提交本次事务 err = tx.Commit() if err != nil { log.Println(err) return } log.Println("事务执行成功") }