• golang数据库操作之gorm X


    人生苦短,let’s Go.

     

    ORM 框架
    ORM:Object Relational Mapping  —— 对象关系映射。

    图片

    作用:

    • 通过操作结构体对象,来达到操作数据库表的目的。

    • 通过结构体对象,来生成数据库表。

    优点:

    • SQL有可能 比较复杂。(Oracle --- 子查询 -- 嵌套)ORM 操作数据库,不需要使用 SQL

    • 不同开发者,书写的 SQL 语句执行效率不同。

    go语言支持的 ORM:gORM , xORM

    [连接数据库]

    import (
     "github.com/jinzhu/gorm"
     _ "github.com/go-sql-driver/mysql"   //"_" 代码不直接使用包, 底层链接要使用!
     "fmt"
    )
    // mysql: 数据库的驱动名
    // 链接数据库 --格式: 用户名:密码@协议(IP:port)/数据库名?xxx&yyy&
    conn, err := gorm.Open("mysql", "root:123456@tcp(127.0.0.1:3306)/test")
    if err != nil {
        fmt.Println("gorm.Open err:",err)
        return
    }
    defer conn.Close()

    创建数据库表。—— 不能使用gorm创建数据库。 提前使用 SQL语句,创建好想要的数据库。
    AutoMigrate() 创建表。默认创建的表为复数类型。—— 自动添加“s”
    在创建之前, 添加  conn.SingularTable(true) 可以创建非复数表名的表。

    // 不要复数表名
    conn.SingularTable(true)
    
    // 借助 gorm 创建数据库表.
    fmt.Println(conn.AutoMigrate(new(Student)).Error)

    MySQL 包的 init 方法

    _ "github.com/go-sql-driver/mysql" 导入包时, “_” ,表示,驱使go系统,在main() 函数被调用之前,自动调用 init() 函数。

    go语言中有两个特殊函数: —— 首字母小写,包外可见

      • main()   —— 项目的入口函数

      • init() —— 当导包,但没有在程序中使用。在main() 调用之前,自动被调用。
        查看:光标置于 MySQL包的 “mysql” 上。使用 Ctrl-鼠标左键。看到源码。在 driver.go 底部包含 init() 函数的 定义。

        init() 作用:实现注册 MySQL 驱动。

    gorm的连接池

    -- 默认,gorm框架创建好的MySQL数据库连接 conn ,就是一个连接池的句柄。
    conn, err := gorm.Open("mysql", "root:123456@tcp(127.0.0.1:3306)/test")

    初始化全局变量, 接收句柄

    // 创建全局连接池句柄
    var GlobalConn *gorm.DB
    GlobalConn = conn

    db.LogMode(false)  是否打印执行SQL

    修改连接池初始属性

    // 初始数
    GlobalConn.DB().SetMaxIdleConns(10)
    // 最大数
    GlobalConn.DB().SetMaxOpenConns(100)

    使用连接池句柄
    --- 对比redis连接池:不需要使用 Get() 方法,取一条连接。

    // 不要复数表名
    GlobalConn.SingularTable(true)
    // 借助 gorm 创建数据库表.
    fmt.Println(GlobalConn.AutoMigrate(new(Student)).Error)

    MySQL 8小时 时区问题

    MySQL默认使用的时间 :美国 东 8 区 时间 。—— 北京时间 —— 差 8 小时。
    在连接数据库时,添加属性:?parseTime=True&loc=Local

    conn, err := gorm.Open("mysql”,"root:123456@tcp(127.0.0.1:3306)/test?parseTime=True&loc=Local")

    再执行SQL语句、gorm访问MySQL 使用 北京时间。

    [SQL操作]

    插入:

    // insert into student(name, age) values('zhangsan', 100)
    
    func InsertData()  {
     // 先创建数据 --- 创建对象
     var stu Student
     stu.Name = "zhangsan"
     stu.Age = 100
    
     // 插入(创建)数据
     fmt.Println(GlobalConn.Create(&stu).Error)
    }

    使用注意事项:

    • 插入数据时,使用的 create() 函数,传参时,必须传入 &对象。如果遗漏 “&” 会报错

    • 要保证 ,在插入数据库时,GlobalConn.SingularTable(true) 生效。代表不使用 复数表名。

    查询:

    简单查询方法:
    First(&user): 获取 user 表中的第一条数据

    func SearchData()  {
     var stu Student
     GlobalConn.First(&stu)
     fmt.Println(stu)
    }

    相当于SQL:SELECT * FROM student ORDER BY id LIMIT 1;

    只查询 nameage 不查询其他值:

    GlobalConn.Select("name, age").First(&stu)

    Last(&user): 获取 user 表中的最后一条数据
    相当于SQL:SELECT * FROM users ORDER BY id DESC LIMIT 1

    Find(&user): 获取 user 表中的所有数据。

    var stu []Student  // 改为切片
    GlobalConn.Select("name, age").Find(&stu)   // Find() 查询多条

    相当于SQL:select name, age from student;

    条件查询:

    select name, age from student where name = 'lisi';
    GlobalConn.Select("name, age").Where("name = ?", "lisi").Find(&stu)
    
    
    select name, age from student where name = 'lisi' and age = 22;
    //方法1:
    GlobalConn.Select("name, age").Where("name = ?", "lisi").
       Where("age = ?", 22).Find(&stu)
    //方法2:
    GlobalConn.Select("name, age").Where("name = ? and age = ?", "lisi", 22).Find(&stu)

    更新:

    Save(): 根据主键更新。如果数据没有指定主键,不更新,变为 “插入”操作。

    func UpdateData()  {
        var stu Student
        stu.Name = "wangwu"
        stu.Age = 99 // 没有指定 id -- 没有主键! --- 插入
        fmt.Println(GlobalConn.Save(&stu).Error)
    }

    更新一个:

    func UpdateData()  {
        var stu Student
        stu.Name = "wangwu"
        stu.Age = 77
        stu.Id = 4  //指定 id -- 更新操作!
        fmt.Println(GlobalConn.Save(&stu).Error)
    }

    Update(): 更新一个字段。

    fmt.Println(GlobalConn.Model(new(Student)).Where("name = ?", "zhaoliu").
                Update("name", "lisi").Error)
    // Model(new(Student): 指定更新 “student” 表

    Updates(): 更新多个字段。

    fmt.Println(GlobalConn.Model(new(Student)).Where("name = ?", "lisi").
                Updates(map[string]interface{}{"name":"liuqi", "age":24}).Error)

    grom 删除数据

    删除:物理删除。真正的执行 Delete

    软删除:逻辑删除。不真正删。不执行Delete

    创建表时,在表中添加一个 “删除字段” 。当需要删除时,更新 “删除字段”, 更新为true
    查询时,不查询 “删除字段” 为 null 的值。

    创建表:

    // 创建全局结构体
    type Student struct {
          gorm.Model // go语言中, 匿名成员 --- 继承! Student 继承 Model
          Name string
          Age int
    }
    // 在“Model”上,Ctrl-B 跳转至 Model 类定义。
    type Model struct {
          ID        uint `gorm:"primary_key"`
          CreatedAt time.Time
          UpdatedAt time.Time
          DeletedAt *time.Time `sql:"index"`
    }
    // Model 表由 mysql自动维护,不需要我们手动维护。

    执行软删除:

    // 使用 Delete() 参数,指定要删除的数据所在表的表名。
    fmt.Println(GlobalConn.Where("name = ?", "lisi").Delete(new(Student)).Error)


    db.Delete(Email{}, "email LIKE ?", "%jinzhu%")

    验证:
    select * from student;  依然能看到 “lisi” 相关数据。但是 。delete_at 字段。被填入数据。

    db.Debug().Delete(u)  debug模式, 打印执行的SQL语句

    在 gorm 框架中,执行 查询语句:

    func SearchData()  {
        var stu []Student
     GlobalConn.Find(&stu)
     fmt.Println(stu)
    }

    --- 查询结果为:[ ]  ---- "软删除" 成功!
    想查询“软删除”的数据:

    GlobalConn.Unscoped().Find(&stu)

    想 实现 “物理删除”
    --- 借助 Unscoped() 执行删除。

    GlobalConn.Unscoped().Where("name = ?", "lisi").Delete(new(Student))

    gorm 设置表属性

    修改表字段大小

    // 创建全局结构体
    type Student struct {
     Id    int
            // string -- varchar。 默认大小255. 可以在创建表时,指定大小。
     Name  string `gorm:"size:100;default:'xiaoming'"`
     Age   int
     Class int    `gorm:"not null"`
    }

    结论:修改表属性,只能在第一次建表的时候,有效!或者给表增加新字段的时候,有效!其他场景,修改表属性 ,在 gorm 操作中,无效!

    设置时间
    默认MySQL数据库 有 3 种时间:

    • date

    • datetime

    • timeStamp:时间戳。——  gorm 中,只有 timeStamp

    如果必须使用 MySQL 数据库特有的 “数据类型”, 使用 “type” 关键字来设置。

    // 创建全局结构体
    type Student struct {
     Id    int
     Name  string    `gorm:"size:100;default:'xiaoming'"`
     Age   int
     Class int       `gorm:"not null"`
     Join  time.Time `gorm:"type:timestamp"`// 创建 Student 表指定 timestamp类型。
    }
  • 相关阅读:
    软件质量的“奥秘”(一)——虚伪的质量
    IT项目管理中的假设约束依赖和承诺
    [转载]IT知识体系结构图
    如何看待项目开发过程中基于度量结果的绩效考评
    我常用的一些ASP自定义函数
    女生永远也不知道男生为什么***
    系统分析员、系统架构师、项目经理的区别
    软件工程知识体系全景图
    my music / NightWish / Groove Coverage / DJ
    qiushibaike.com
  • 原文地址:https://www.cnblogs.com/xingxia/p/golang_gorm.html
Copyright © 2020-2023  润新知