26

golang gorm(一)---gorm入门示例

 3 years ago
source link: https://studygolang.com/articles/30456
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

gorm是go语言的一个orm框架,框架的原理和思想在这里就不做详细介绍了,我主要演示一下gorm的实际使用。

开启mysql连接

主要用到 gorm.open()这个方法

//参数含义:数据库用户名、密码、主机ip、连接的数据库、端口号
func dbConn(User, Password, Host, Db string, Port int) *gorm.DB {
    connArgs := fmt.Sprintf("%s:%s@(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local", User, Password, Host, Port, Db)
    db, err := gorm.Open("mysql", connArgs)
    if err != nil {
        return nil
    }
    db.SingularTable(true)          //如果使用gorm来帮忙创建表时,这里填写false的话gorm会给表添加s后缀,填写true则不会
    db.LogMode(true)                //打印sql语句
    //开启连接池 
    db.DB().SetMaxIdleConns(100)        //最大空闲连接
    db.DB().SetMaxOpenConns(10000)      //最大连接数
    db.DB().SetConnMaxLifetime(30)      //最大生存时间(s)

    return db
}

func GetDb() (conn *gorm.DB) {
    for {
        conn = dbConn("root", "123456", "127.0.0.1", "test", 3306)
        if conn != nil {
            break
        }
        fmt.Println("本次未获取到mysql连接")
    }
    return conn
}

CRUD操作

User是与数据库表对应的结构体, gorm:"primary_key" json:"id" 这个记得加在主键后面,非常重要,后面会讲为什么。

type User struct {
    Id      int     `gorm:"primary_key" json:"id"`
    Name    string  `json:"name"`
    Age     int     `json:"age"`
    Gender  int     `json:"gender"`     //1:男、2:女
}

//添加数据
func (user *User) Add() {
    conn := db.GetDb()
    defer conn.Close()

    err := conn.Create(user).Error
    if err != nil {
        fmt.Println("创建失败")
    }
}

//修改数据
func (user *User) Update() {
    conn := db.GetDb()
    defer conn.Close()

    err := conn.Model(user).Update(user).Error
    if err != nil {
        fmt.Println("修改失败")
    }
}

//删除数据
func (user *User) Del() {
    conn := db.GetDb()
    defer conn.Close()

    err := conn.Delete(user).Error
    if err != nil {
        fmt.Println("删除失败")
    }
}

这里演示一下实际的数据库增删改操作

//添加,这里要注意,上面提到了gorm:"primary_key" json:"id"这个东西,只要在主键id后面加了这个,gorm就会在生成数据之后把主键返回到user中
func TestAdd(t *testing.T) {
    user := new(entity.User)
    user.Name = "tome"
    user.Age = 18
    user.Gender = 1
    user.Add()          //user.id = 1,添加之后user中的id会变成数据库中生成的值
}
e2q6Rv6.png!mobile

添加

//修改
func TestUpdate(t *testing.T) {
    user := new(entity.User)
    user.Id = 1             //修改需要知道主键id,当然也可以条件修改
    user.Name = "jack"
    user.Update()
}
VBZRbqb.png!mobile

修改

//删除
func TestDel(t *testing.T) {
    user := new(entity.User)
    user.Id = 1
    user.Del()
}
FZnAfa.png!mobile

删除

这一节就只演示增删改,关于查询我想放在后面单独讲,因为查询这一块涉及到的东西比较多,后面我也会把echo和gorm整合起来做一个demo放出来。

有疑问加站长微信联系

iiUfA3j.png!mobile

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK