This article learning video https://www.bilibili.com/video/BV1Bz411v78U/?spm_id_from=333.788
Chinese Gorm official document https://jasperxu.com/Programming/Golang/GORM/
Another document https://learnku.com/docs/gorm/v2/index/9728
What is ORM
- An auxiliary tool for database operation
- Map between our go structure and the database, so that we can intuitively reflect the relationship of the database and the content of the table on the structure
- You can add, delete, modify and query by using the structure
How to connect to the database
- Introduce Gorm package GitHub com/jinzhu/gorm
- Introduce MySQL driver package GitHub com/go-sql-driver/mysql
- Establish a database connection for the first time. The code is as follows
package main
import (
_ "github.com/go-sql-driver/mysql"
"github.com/jinzhu/gorm"
)
func main() {
db, err := gorm.Open("mysql",
"root:[email protected]/ginclass?charset=utf8mb4&parseTime=True&loc=Local")
defer db.Close()
if err != nil {
panic(err)
}
}
Creating tables with grom
Use dB Automigrate to create a table. Description: dB Automigrate will automatically determine whether the table exists. If it does not exist, create a table.
package main
import (
_ "github.com/go-sql-driver/mysql"
"github.com/jinzhu/gorm"
)
type HelloWorld struct {
gorm.Model
Name string
Sex bool
Age int
}
func main() {
db, err := gorm.Open("mysql",
"root:[email protected]/ginclass?charset=utf8mb4&parseTime=True&loc=Local")
defer db.Close()
if err != nil {
panic(err)
}
//db. Automigrate determines whether a table exists. If it does not exist, it will be created automatically
db.AutoMigrate(&HelloWorld{})
}
Gorm. In the HelloWorld structure Model is a golang structure that contains four fields: ID, createdat, updatedat and deletedat. These fields will be created automatically when creating a table.
The structure after table building is as follows
After the basic operations of adding and deleting tables are completed.
Increase operation
Use dB Create to create a piece of data whose name is Kaka, sex is true and age is 21
package main
import (
_ "github.com/go-sql-driver/mysql"
"github.com/jinzhu/gorm"
)
type HelloWorld struct {
gorm.Model
Name string
Sex bool
Age int
}
func main() {
db, err := gorm.Open("mysql",
"root:[email protected]/ginclass?charset=utf8mb4&parseTime=True&loc=Local")
defer db.Close()
if err != nil {
panic(err)
}
//db. Automigrate determines whether a table exists. If it does not exist, it will be created automatically
db.AutoMigrate(&HelloWorld{})
//Create data
db.Create(&HelloWorld{
Name: "kaka",
Sex: true,
Age: 21,
})
}
After running, you can see that there is one more piece of data in the table.
Let’s create two pieces of data to check.
Check operation
- db. First method use
We use dB First, check the first data in the database
The results after operation are as follows
Specify criteria for query
The query results are as follows
- db. Find method usage
Note: dB When you find, you should accept the address of a slice
The code is as follows
The printing results are as follows
You can see that without conditions, DB Find found all the results.
We add the condition where sex = false to query
The code is as follows
give the result as follows
Generally, in the actual development process, where will be written in the front. The example is as follows
The or statement is relatively simple and can be written in where or dB where(). Or. Find()
Change operation
db. Update() to modify a single field
Change the value of the name field in the data with ID 1 in the HelloWorld table to Jack
The code is as follows
db. Updates() to modify multiple fields
If there is an empty attribute in updates (HelloWorld {}), such as age = 0, name = “”, or sex = false, these fields will not be modified.
If you want to change the field to these empty attributes, such as changing age to 0, you need to add a map
The code is as follows
If you want to modify multiple pieces of data, such as ID in 1 and 2, change them
The code is as follows
Note that slices should be added to the first method
Delete operation
Use dB Delete method
However, this deletion is a soft deletion, as shown in the figure below
Delete the data with ID 1 and 2. The code is as follows
This is also a soft deletion. If you want to make a hard deletion, you need to add the unscoped () method
The code is as follows
summary
- Create connection
- db, err := gorm.Open(“mysql”,
“root:[email protected]/ginclass?charset=utf8mb4&parseTime=True&loc=Local”)
defer db.Close()
- db, err := gorm.Open(“mysql”,
- Build table
- First define a structure, such as HelloWorld
- Then dB Automigrate (& HelloWorld {}) to create tables
- Increase operation
- db.Create(&HelloWorld{
Name: “kaka”,
Sex: true,
Age: 21,
}) - &HelloWorld {} indicates which table to specify
- db.Create(&HelloWorld{
- Check operation
- db. First() to check the first data in the database
- db. Add where in first() to find conditions
- db. Find(), and a structure slice needs to be specified in the method
- db.Where.Find()
- Change operation
- db. Update() modifies a single field of a single piece of data
- db. Updates() modifies multiple fields of a single piece of data
- db. Updates() method to change the field to 0 value, such as false, number 0 and empty string
- db. Updates() method for modifying multiple pieces of data
- Delete operation
- db. Delete() soft delete
- db. Where(). Unscoped(). Delete() hard delete