安装

1
2
go get -u gorm.io/gorm
go get -u gorm.io/driver/mysql

连接数据库

dsn格式

1
dsn := "user:pass@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local"

开始

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
package main

import (
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)

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

var (
DB *gorm.DB
)

const dns = "root:123456@tcp(127.0.0.1:3306)/test?charset=utf8mb4&parseTime=True&loc=Local"


func main() {
db, err := gorm.Open(mysql.Open(dns), &gorm.Config{Logger: logger.Default.LogMode(logger.Info)})
//开启debug模式,打印出sql语句
if err != nil {
panic("failed to connect database")
}

db.AutoMigrate(&Product{})
////自动识别表有没有创建,有没有新增,并自动创建或者迁移等

db.Create(&Product{Code: "D42", Price: 100})

}