mysql database connection
import (
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
const (
mysqlHost = "go-uccs"
mysqlPort = 3306
mysqlUser = "uccs"
mysqlPassword = 123456
mysqlDbname = "uccs"
)
dsn := fmt.Sprintf("%s:%d@tcp(%s:3306)/%s", mysqlUser, mysqlPassword, mysqlHost, mysqlDbname)
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
Configure global logger
newLogger := logger.New(
log.New(os.Stdout, "\r\n", log.LstdFlags),
logger.Config{
SlowThreshold: time.Second, // Slow SQL threshold
LogLevel: logger.Silent, // Log level
Colorful: false, // Disable colors
},
)
gorm.Open(mysql.Open(dsn), &gorm.Config{newLogger})
log.LstdFlags
: Indicates that the date and time of the local time zone should be added when outputting logs. The output format is: : 2023/07/14 21:28:20 Hello, world!
SlowThreshold
Set the slow SQL
threshold. If SQL
the execution time exceeds this threshold, it will be recorded as slow SQL
LogLevel
: Set the log level, and gorm
four log levels are defined: Silent
, Error
, Warn
, Info
. You can choose the appropriate log level according to your needs Colorful
: set whether to use colored fonts to display logs, if set false
, it will disable colored fonts
build table
type Product struct {
gorm.Model
Code string
Price uint
}
db.AutoMigrate(&Product{})
gorm.Model
Is a structure, which is gorm
a general model defined in the package, including four fields ID
, CreatedAt
, UpdatedAt
,DeletedAt
CRUD
Create a new data
db.Create(&Product{Code: "D42", Price: 100})
corresponding SQL
statement
INSERT INTO `products` (`created_at`,`updated_at`,`deleted_at`,`code`,`price`) VALUES ('2023-07-15 03:39:37.951','2023-07-15 03:39:37.951',NULL,'D42',100)
Inquire
Find a piece of data
Use First
to find data, the default search does not contain soft deleted data
var product Product
db.First(&product, 1) // 查找主键为 1 的数据
corresponding SQL
statement
SELECT * FROM `products` WHERE `products`.`id` = 1 AND `products`.`deleted_at` IS NULL ORDER BY `products`.`id` LIMIT 1
conditional search
db.First(&product, "code = ?", "D42") // 查找 code 字段值为 D42 的第一条数据
corresponding SQL
statement
SELECT * FROM `products` WHERE code = 'D42' AND `products`.`deleted_at` IS NULL ORDER BY `products`.`id` LIMIT 1
mistake
Returns ErrRecordNotFound
error if data not found
ok := errors.Is(result.Error, gorm.ErrRecordNotFound)
query all data
var products []Product
db.Find(&products)
for _, product := range products {
fmt.Println(product)
}
corresponding SQL
statement
SELECT * FROM `products` WHERE `products`.`deleted_at` IS NULL
renew
db.Model(&product).Where("code = ?", "D42").Update("Price", 300)
corresponding SQL
statement
UPDATE `products` SET `price`=300,`updated_at`='2023-07-15 03:47:29.659' WHERE code = 'D42' AND `products`.`deleted_at` IS NULL
update multiple values
db.Model(&product).Where("code = ?", "D42").Updates(Product{Price: 200, Code: "F42"})
corresponding SQL
statement
UPDATE `products` SET `updated_at`='2023-07-15 03:50:35.218',`code`='F42',`price`=200 WHERE code = 'D42' AND `products`.`deleted_at` IS NULL
db.Model(&product).Where("code = ?", "F42").Updates(map[string]interface{}{"Price": 300, "Code": "D42"})
corresponding SQL
statement
UPDATE `products` SET `code`='D42',`price`=300,`updated_at`='2023-07-15 03:53:26.329' WHERE code = 'F42' AND `products`.`deleted_at` IS NULL
save method
save
The method will save fields that have not been assigned a value, and the default value is zero
type User {
Name string `gorm:"column:user_name"`
Email string
}
user := User{Name: "uccs1"}
db.Save(&user)
corresponding SQL
statement
INSERT INTO `users` (`user_name`,`email`) VALUES ('uccs1','')
Select and Omit
var user User
db.Model(&user).Where("user_id = ?", 1).Select("Email").Updates(User{Name: "uccs2", Email: "333"})
db.Model(&user).Where("user_id = ?", 1).Omit("Email").Updates(User{Name: "uccs333", Email: "333"})
corresponding SQL
statement
UPDATE `users` SET `email`='333' WHERE user_id = 1
UPDATE `users` SET `user_name`='uccs333' WHERE user_id = 1
delete
db.Delete(&product, 1)
corresponding SQL
statement
UPDATE `products` SET `deleted_at`='2023-07-15 03:57:07.889' WHERE `products`.`id` = 1 AND `products`.`deleted_at` IS NULL
If a Model
has gorm.DeletedAt
type, it will automatically get the function of soft deletion, deleted_at
write the deletion time in the field, and when querying data, it will automatically ignore deleted_at
the data whose field is not empty
Permanent deletion can be done using Unscoped
the method
update only non-zero values
Use Updates(Product{Price: 0})
the method to update, only non-zero values can be updated
Because go
in , if a field has no value, it will have a default value, which is usually zero value
这时,就想更新一个字段为零值可以用 sql.NullString
类型,int
类型有 NullInt16
等
type Product {
Code sql.NullString
}
db.Model(&product).Where("code = ?", "D42").Updates(&Product{Code: sql.NullString{"", true}})
另一种是使用指针的形式
type Product {
Code *string
}
empty := ""
db.Model(&product).Where("code = ?", "D42").Updates(&Product{Code: &empty})
对应 SQL
语句
UPDATE `products` SET `updated_at`='2023-07-15 09:13:38.229',`code`='' WHERE code = 'D42' AND `products`.`deleted_at` IS NULL
表结构定义的细节
使用 tag
就可以自定义表结构,具体可以看文档:Declaring Models
type User struct {
UserId int `gorm:"primaryKey"`
Name string `gorm:"column:user_name;type:varchar(100);not null;index:idx_user_name;unique;default:'uccs'"`
}
创建记录
// 没有 ID
user := User{
Name: "uccs2",
}
result := db.Create(&user)
fmt.Println(result.Error)
fmt.Println(result.RowsAffected)
// 执行完 db.Create 后,会有一个 ID
fmt.Println(user.ID)
批量创建
user := []User{{Name: "uccs21"}, {Name: "uccs31"}, {Name: "uccs41"}}
db.Create(&user)
对应的 SQL
语句
INSERT INTO `users` (`user_name`) VALUES ('uccs21'),('uccs31'),('uccs41')
使用 db.CreateInBatches
批量创建,每次创建 2
条
user := []User{{Name: "uccs21"}, {Name: "uccs31"}, {Name: "uccs41"}}
db.CreateInBatches(user, 2)
对应的 SQL
语句
INSERT INTO `users` (`user_name`) VALUES ('uccs21'),('uccs31')
INSERT INTO `users` (`user_name`) VALUES ('uccs41')
条件查询
查询条件有三种形式:string
、struct
、map
// string
db.Where("name = ?", "uccs").First(&user) // name 是数据库 column
// struct
db.Where(&User{MyName: "uccs"}).First(&user) // MyName 是 User 结构体的字段
// map
db.Where(map[string]interface{}{"name": "uccs"}).Find(&user)
要注意的是:使用 struct
形式作为条件,会屏蔽掉零值字段