preface

In daily development, it is inevitable to deal with the database, so how to operate the database in go ORM way? Let’s try it this time!

The connection

First we need to introduce GORM:

go get -u gorm.io/gorm
go get -u gorm.io/driver/mysql
Copy the code

Then write the method to connect to the database:

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

func ConnectDB(host, name, username, password string, port int) (db *gorm.DB, err error) {
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s? charset=utf8mb4", username, password, host, port, name)
	db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	return
}
Copy the code

The migration

Gorm with transfer function, specific see: migration | gorm, here we need to define our data model (see model for specific rules can define | gorm) :

type Student struct {
	Id int `gorm:"primaryKey; autoIncrement"`
	Name string `gorm:"type:varchar(10); not null"`
	Age int `gorm:"type:int(3); not null"`
	Address string `gorm:"type:varchar(50); not null"`
}
Copy the code

Then perform the migration:

func main(a) {
	db, err := ConnectDB("127.0.0.1"."juejin"."root"."root".3306)
	iferr ! =nil {
		panic(err)
	}
	err = db.AutoMigrate(&Student{})
	iferr ! =nil {
		panic(err)
	}
}
Copy the code

Basic operation

Insert data

func InsertData(db *gorm.DB) {
	loop := 10
	students := make([]Student, 0, loop)
	for i := 1; i <= loop; i++ {
		students = append(students, Student{
			Name: fmt.Sprintf("Students % d", i),
			Age: i * 2,
			Address: fmt.Sprintf(No. % D, XXX City, XXX Province, i),
		})
	}
	err := db.Create(students).Error
	iferr ! =nil {
		panic(err)
	}
}
Copy the code

Query data

func FindStudentById(db *gorm.DB, id int) (res Student) {
	err := db.Model(&Student{}).First(&res, id).Error
	iferr ! =nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		Error is also returned if no record is found in gorm, see https://gorm.io/zh_CN/docs/query.html
		panic(err)
	}
	return
}
Copy the code

Update the data

func UpdateStudentNameById(db *gorm.DB, id int, newName string) (res bool) {
	rows := db.Model(&Student{}).Where(&Student{Id: id}).Updates(&Student{Name: newName}).RowsAffected
	if rows > 0 {
		res = true
	}
	return
}
Copy the code

Delete the data

func RemoveStudentById(db *gorm.DB, id int) (res bool) {
	rows := db.Model(&Student{}).Delete(&Student{Id: id}).RowsAffected
	if rows > 0 {
		res = true
	}
	return
}
Copy the code

Afterword.

This article is just a simple introduction to gorM usage, you can refer to the official Chinese documentation, which has more detailed examples: GORM Chinese documentation.

Finally, thank you for reading. Thank you!