Post

Golang Mysql Gorm

Gorm 概述

官网 gorm 对数据库的操作

环境搭建

下载依赖

go get -u github.com/jinzhu/gorm

实例(连接)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package main

import (
	"fmt"
	"github.com/Cc360428/HelpPackage/UtilsHelp/logs" // logs
	"github.com/jinzhu/gorm"                         // gorm
	_ "github.com/jinzhu/gorm/dialects/mysql"        // 导入初始化包
)

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

func main() {
	db, err := gorm.Open(Databases.Type, // 连接属性 (mysql)
		fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8&parseTime=True&loc=Local",
			Databases.User,     // 用户名
			Databases.Password, // 密码
			Databases.Host,     // 端口号
			Databases.Name)) // 数据库名字
	if err != nil {
		logs.Error("mysql 连接错误!", err.Error())
	}
	 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)
}

模型定义 struct

Struct 标记

标记 实义
column 指定列名
type ~~数据类型
size ~~大小,默认 255
primary_key ~~主键
unique ~~唯一
default ~~默认值
precision ~~精度
not null ~~非空
auto_increment ~~自增类型
index 创建索引
unique_index ~~唯一索引
embedde 将结构体设置为嵌入
embedde_prefix 设置嵌入结构的前缀
- 忽略此字段

User struct Test

1
2
3
4
5
6
7
8
9
10
type User struct{
    gorm.Model //  自增id 添加时间 修改时间 软删除时间
    Name string `gorm:"type:varchar(100);unique_index"` // 类型 varchar 唯一索引
    Address string `gorm:"size(22)"`// 设置大小
    Image string `gorm:"unique;not null"` // 唯一 且不为空
    Age int `gorm:"index:age"` // 给age字段创建age索引
    Demo string `gorm:"-"` // 忽略该字段
    Test int `gorm:"auto_increment"`  // 设置自增

}
This post is licensed under CC BY 4.0 by the author.