gorm使用

1. introduction

读完官网的例子就差不多了。
https://gorm.io/zh_CN/docs/index.html
https://gorm.io/zh_CN/docs/conventions.html

2. 例子

package main

import (
  "github.com/jinzhu/gorm"
  _ "github.com/jinzhu/gorm/dialects/sqlite"
)

type Product struct {
  gorm.Model
  Code string
  Price uint
}

func main() {
  db, err := gorm.Open("sqlite3", "test.db")
  if err != nil {
    panic("failed to connect database")
  }
  defer db.Close()

  // Migrate the schema
  db.AutoMigrate(&Product{})

  // 创建
  db.Create(&Product{Code: "L1212", Price: 1000})

  // 读取
  var product Product
  db.First(&product, 1) // 查询id为1的product
  db.First(&product, "code = ?", "L1212") // 查询code为l1212的product

  // 更新 - 更新product的price为2000
  db.Model(&product).Update("Price", 2000)

  // 删除 - 删除product
  db.Delete(&product)
}

3. gorm.Model

type Model struct {
  ID        uint `gorm:"primary_key"`
  CreatedAt time.Time
  UpdatedAt time.Time
  DeletedAt *time.Time
}

嵌了gorm.Model就相当于加了4个字段,ID是主键。gorm会给DeletedAt字段创建索引。

不内嵌gorm.Model也行,可以自己指定primary key。

4. table name

db.Create(&Product{Code: "L1212", Price: 1000})

db的操作是直接create,没有指定table,默认会将struct的名字的复数当成表名。
你也可以通过db.SingularTable(true) 来禁止变成复数,或者通过db.Table(..).来指定table。

5. 时间类型

time.Time ,但是如果这个字段为空,想设成NULL ,那么就需要定义成*time.Time指针。
字符串到时间的转化可以用time.Parse()。

6. gorm在mysql下乱码问题

这个有点蛋疼,用sqlite3一点乱码问题都没有,用mysql,中文死活插入不了,

光在mysql连接串里面指定utf 把是不行的

db, err = gorm.Open("mysql","gorm:gorm@tcplocalhost:9910)/gorm?charset=utf8mb4,utf8&parseTime=True")

修改mysql 配置:

    [client]
    default-character-set=utf8
    [mysql]
    default-character-set=utf8
    [mysqld]
    character-set-server=utf8

然后再设置 table_options,

db.Set("gorm:table_options", "CHARSET=utf8").AutoMigrate{ ... }

可以解决乱码问题,如果遇到此类问题,用show create table查看table的charset,如果不是utf8,就就说明gorm生成的时候有问题,通过上面的语句能修正。

posted @ 2020-06-02 14:34  过去的我  阅读(1533)  评论(0编辑  收藏  举报