How do you use GORM to operate a database in Go language?
To manipulate databases using GORM in Go language, the first step is to install the GORM library. This can be done by using the following command:
go get -u gorm.io/gorm
go get -u gorm.io/driver/mysql
After installation, you can create a database connection and instantiate a gorm.DB object for database operations. Example code is as follows:
import (
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
func main() {
dsn := "username:password@tcp(localhost:3306)/database?charset=utf8mb4&parseTime=True&loc=Local"
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
panic("failed to connect database")
}
// 定义模型结构
type User struct {
gorm.Model
Name string
Email string
}
// 创建表
err = db.AutoMigrate(&User{})
if err != nil {
panic("failed to migrate database")
}
// 创建记录
user := User{Name: "John", Email: "john@example.com"}
db.Create(&user)
// 查询记录
var result User
db.First(&result, user.ID)
fmt.Println(result)
// 更新记录
db.Model(&result).Update("Name", "Tom")
// 删除记录
db.Delete(&result)
}
The example code above demonstrates how to use GORM to create connections, tables, records, query records, update records, and delete records. It can be adjusted and expanded based on your own needs.