go-mysql

go-mysql_第1张图片

 

 go-mysql_第2张图片

package main

import (
    "database/sql"
    "fmt"

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

func main() {
    db, err := sql.Open("mysql", "root:root@/test?charset=utf8")
    checkErr(err)

    //插入数据
    stmt, err := db.Prepare("INSERT INTO userinfo SET username=?,department=?,created=?")
    checkErr(err)

    res, err := stmt.Exec("root", "研发部门", "2019-12-21")
    checkErr(err)

    id, err := res.LastInsertId()
    checkErr(err)

    fmt.Println("id: ", id)
    //更新数据
    stmt, err = db.Prepare("update userinfo set username=? where uid=?")
    checkErr(err)

    res, err = stmt.Exec("xxc", id)
    checkErr(err)

    affect, err := res.RowsAffected()
    checkErr(err)

    fmt.Println("affect: ", affect)

    //查询数据
    rows, err := db.Query("SELECT * FROM userinfo")
    checkErr(err)

    for rows.Next() {
        var uid int
        var username string
        var department string
        var created string
        err = rows.Scan(&uid, &username, &department, &created)
        checkErr(err)
        fmt.Println("uid: ", uid)
        fmt.Println("username: ", username)
        fmt.Println("department: ", department)
        fmt.Println("created: ", created)
    }

    //删除数据
    stmt, err = db.Prepare("delete from userinfo where uid=?")
    checkErr(err)

    res, err = stmt.Exec(id)
    checkErr(err)

    affect, err = res.RowsAffected()
    checkErr(err)

    fmt.Println("affect: ", affect)

    db.Close()

}

func checkErr(err error) {
    if err != nil {
        panic(err)
    }
}

go-mysql_第3张图片

你可能感兴趣的:(go-mysql)