Golang之Mysql事务

Mysql事务
1)原子性
2)一致性
3)隔离性
4)持久性

示例代码

package main

import (
    "fmt"
    _ "github.com/go-sql-driver/mysql" //初始化一个mysql驱动,必须
    "github.com/jmoiron/sqlx"
)

type Person struct {
    UserId   int    `db:"user_id"`
    Username string `db:"username"`
    Sex      string `db:"sex"`
    Email    string `db:"email"`
}
type Place struct {
    Country string `db:"country"`
    City    string `db:"city"`
    TelCode int    `db:"telcode"`
}

var Db *sqlx.DB

func init() {
    //"mysql"指定数据库类型,  /test指定打开的数据库  root:123 冒号隔开密码 root账号 123密码
    database, err := sqlx.Open("mysql", "root@tcp(127.0.0.1:3306)/test")
    if err != nil {
        fmt.Println("open mysql failed,", err)
        return
    }
    Db = database
}
func main() {
    //事务操作
    conn, err := Db.Begin()
    if err != nil {
        return
    }

    //插入数据入表
    r, err := Db.Exec("insert into person(username,sex,email)values(?,?,?)", "chaoge", "man", "yc_uuu@163.com")
    if err != nil {
        fmt.Println("exec failed,", err)
        return
    }

    id, err := r.LastInsertId()
    if err != nil {
        fmt.Println("exec failed,", err)
        //回滚
        conn.Rollback()
        return
    }
    fmt.Println("insert succ:", id)
    //提交事务 conn.Commit() }

 

posted @ 2018-02-03 14:47  py鱼  阅读(8441)  评论(4编辑  收藏  举报
点我回主页