The use of gorm

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.

  1. 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()
  1. 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.

  1. 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.

  1. 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)
  1. 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

Guess you like

Origin blog.csdn.net/ekcchina/article/details/131103924