GORM in Golang is a very popular ORM (Object Relational Mapping) library when it comes to database operations. It provides a concise and powerful API, making database operations easier and more efficient. In this technical sharing article, we will explore some core functions and usage of GORM.
- Installation and Initialization
First, we need to install GORM. Run the following command in a terminal:
go get -u gorm.io/gorm
go get -u gorm.io/driver/<your-database-driver>
Among them is the database driver you are using, such as mysql, postgres, etc. After the installation is complete, we can start using GORM.
Import GORM in code:
Copy code
import "gorm.io/gorm"
Then, create a database connection:
dsn := "<your-dsn>" // 数据库连接字符串
db, err := gorm.Open(<your-database-driver>, dsn)
if err != nil {
// 处理错误
}
defer db.Close()
- Defining Models and Data Tables
In GORM, we can use structs to define models for database tables. Each structure field corresponds to a column in the table.
type User struct {
gorm.Model
Name string
Email string
Age int
}
The above example defines a model called User that contains some common fields. gorm.Model is a built-in model provided by GORM for automatically adding ID, CreatedAt, UpdatedAt and DeletedAt fields.
- Database migration
GORM provides the function of database migration, which can automatically create and update database tables according to the model definition.
Create table:
db.AutoMigrate(&User{})
The above code checks to see if the users table exists in the database and creates it if not.
- CRUD operations
GORM provides a wealth of methods to perform CRUD operations.
Create record:
user := User{Name: "John", Email: "[email protected]", Age: 25}
db.Create(&user)
Read records:
var user User
db.First(&user, 1) // 通过主键获取第一条记录
update record:
db.Model(&user).Update("Age", 30)
Delete Record:
db.Delete(&user)
- Query Builder
GORM provides a query builder that makes complex queries easy.
var users []User
db.Where("age > ?", 18).Find(&users)
The preceding code queries for all users whose age is greater than 18.
Author: Lu Zhengchao