GO链接MySql的CURD

上代码

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)/databaseT?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
}

//根据Id查询
func queryRow(id int) {
    var u1 User
    sqlStr := "select Id,Name,Age from User where Id=?;"
    //执行
    rowObj := Db.QueryRow(sqlStr, id)
    //赋值并关闭链接(Scan方法)
    rowObj.Scan(&u1.Id, &u1.Name, &u1.Age)
    fmt.Printf("Id:%v;Name:%v;Age:%v;\n", u1.Id, u1.Name, u1.Age)
}

//查询
func query(where string) {
    sqlStr := "select Id,Name,Age from User " + where + ";"
    //执行
    rows, err := Db.Query(sqlStr)
    if err != nil {
        fmt.Println("查询错误:%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 insert(insertStr string) (id int64) {
    ret, err := Db.Exec(insertStr)
    if err != nil {
        fmt.Printf("插入数据异常,错误%v \n", err)
        return
    }
    ids, err := ret.LastInsertId()
    if err != nil {
        fmt.Printf("获取ID,错误:%v\n", err)
        return
    }
    return ids
}

//更新
func update(id int, newName string, newAge int) (rows int64) {
    ret, err := Db.Exec("update User set Name=?,age=? where Id = ?", newName, newAge, id)
    if err != nil {
        fmt.Printf("更新数据异常,错误%v \n", err)
        return
    }
    n, err := ret.RowsAffected()
    if err != nil {
        fmt.Printf("更新 %v 失败,错误:%v\n", newName, err)
        return
    }
    return n
}

//删除
func delete(id int) (rows int64) {
    ret, err := Db.Exec("delete from User where Id = ?", id)
    if err != nil {
        fmt.Printf("删除数据异常,错误%v \n", err)
        return
    }
    n, err := ret.RowsAffected()
    if err != nil {
        fmt.Printf("删除失败,错误:%v\n", err)
        return
    }
    return n
}

func main() {
    err := initDB()
    if err != nil {
        fmt.Printf("初始化失败,错误%v\n", err)
        return
    }
    fmt.Println("数据库链接成功。")
    queryRow(1)
    fmt.Println("-----------------------------------")
    id := insert("insert into User(Name,Age) values ('dzw120',22);")
    fmt.Printf("ID:%v\n", id)
    fmt.Println("-----------------------------------")
    query("where id > 0")
    fmt.Println("-----------------------------------")
    affectRow := update(4, "李晓楠", 23)
    fmt.Printf("受影响行数%v\n", affectRow)
    fmt.Println("-----------------------------------")
    query("where id > 0")
    fmt.Println("-----------------------------------")
    deleteRow := delete(5)
    fmt.Printf("受影响行数%v\n", deleteRow)
    fmt.Println("-----------------------------------")
    query("where id > 0")
}

注:删除的 delete from User,这个【from】在MySql无法省略(不像C#中的MSSQL)

 

效果:

 

 

 

 

 

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

https://www.liwenzhou.com/posts/Go/go_mysql/

 

posted @ 2021-07-01 16:34  蜗牛的礼物  阅读(49)  评论(0编辑  收藏  举报