使用 GORM连接数据库,并实现增删改查操作(实践)| 青训营

112 阅读4分钟

使用GORM连接数据库并实现增删改查操作

“The fantastic ORM library for Golang aims to be developer friendly.”

GORM是Go语言中一个流行的ORM(对象关系映射)库,对开发人员很友好。它提供了简单、高效的方法来连接数据库并执行各种数据库操作。其中,ORM指Object-Relationl Mapping,即对象关系映射,这里的Relationl指的是关系型数据库。它的作用是在关系型数据库和对象之间作一个映射,通过这个操作,我们在具体的操作数据库的时候,就不需要再去研究复杂的SQL语句,只要像平时操作对象一样操作它就可以了。

GORM具有以下特性

  • 全功能 ORM
  • 关联 (Has One,Has Many,Belongs To,Many To Many,多态,单表继承)
  • Create,Save,Update,Delete,Find 中钩子方法
  • 支持 PreloadJoins 的预加载
  • 事务,嵌套事务,Save Point,Rollback To Saved Point
  • Context、预编译模式、DryRun 模式
  • 批量插入,FindInBatches,Find/Create with Map,使用 SQL 表达式、Context Valuer 进行 CRUD
  • SQL 构建器,Upsert,数据库锁,Optimizer/Index/Comment Hint,命名参数,子查询
  • 复合主键,索引,约束
  • Auto Migration
  • 自定义 Logger
  • 灵活的可扩展插件 API:Database Resolver(多数据库,读写分离)、Prometheus…
  • 每个特性都经过了测试的重重考验
  • 开发者友好

本文将介绍如何使用GORM连接数据库,并实现增、删、改、查等操作。

1. 安装和导入GORM

首先,我们需要在Go项目中安装并导入GORM。可以使用以下命令安装GORM:

go get -u gorm.io/gorm

然后,在Go代码中导入GORM:

import (
    "gorm.io/gorm"
    "gorm.io/driver/mysql" // 选择适合你的数据库驱动
)

2. 连接数据库

连接数据库是使用GORM的第一步。gorm支持多种数据库连接,GORM 官方支持的数据库类型有:MySQL, PostgreSQL, SQLite, SQL Server 和 TiDB。在本例中,我们使用MySQL作为示例数据库。在连接之前,确保你已经安装了MySQL数据库,并创建了一个数据库。

func main() {
    // 连接数据库
    dsn := "user:password@tcp(host:port)/dbname?charset=utf8mb4&parseTime=True&loc=Local"
    db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
    if err != nil {
        panic("无法连接数据库")
    }
    
    defer db.Close()
    
    // 后续操作
}

3. 定义数据模型

在GORM中,我们需要定义数据模型来映射数据库表。模型是标准的 struct,由 Go 的基本数据类型、实现了 Scanner 和 Valuer 接口的自定义类型及其指针或别名组成。以下是一个简单的示例:

type User struct {
    gorm.Model
    Username     string
    Email        string
    Age          uint8
    Birthday     *time.Time
    MemberNumber sql.NullString
    ActivatedAt  sql.NullTime
    CreatedAt    time.Time
    UpdatedAt    time.Time
}

4. 增删改查操作

4.1 插入数据

func createRecord(db *gorm.DB) {
    user := User{
        Username: "john",
        Email:    "john@example.com",
    }
    result := db.Create(&user)
    if result.Error != nil {
        fmt.Println("插入失败:", result.Error)
    } else {
        fmt.Println("插入成功")
    }
}

4.2 查询数据

func queryRecords(db *gorm.DB) {
    var users []User
    result := db.Find(&users)
    if result.Error != nil {
        fmt.Println("查询失败:", result.Error)
    } else {
        fmt.Println("查询结果:", users)
    }
}

4.3 更新数据

func updateRecord(db *gorm.DB, id int) {
    var user User
    result := db.First(&user, id)
    if result.Error != nil {
        fmt.Println("查询失败:", result.Error)
        return
    }
    
    user.Email = "new_email@example.com"
    result = db.Save(&user)
    if result.Error != nil {
        fmt.Println("更新失败:", result.Error)
    } else {
        fmt.Println("更新成功")
    }
}

4.4 删除数据

func deleteRecord(db *gorm.DB, id int) {
    var user User
    result := db.First(&user, id)
    if result.Error != nil {
        fmt.Println("查询失败:", result.Error)
        return
    }
    
    result = db.Delete(&user)
    if result.Error != nil {
        fmt.Println("删除失败:", result.Error)
    } else {
        fmt.Println("删除成功")
    }
}

5. 完整示例

以下是一个完整的示例,演示如何使用GORM连接数据库并实现增删改查操作:

package main

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

type User struct {
    gorm.Model
    Username string
    Email    string
    Age          uint8
    Birthday     *time.Time
    MemberNumber sql.NullString
    ActivatedAt  sql.NullTime
    CreatedAt    time.Time
    UpdatedAt    time.Time
}

func createRecord(db *gorm.DB) {
    user := User{
        Username: "john",
        Email:    "john@example.com",
    }
    result := db.Create(&user)
    if result.Error != nil {
        fmt.Println("插入失败:", result.Error)
    } else {
        fmt.Println("插入成功")
    }
}

func queryRecords(db *gorm.DB) {
    var users []User
    result := db.Find(&users)
    if result.Error != nil {
        fmt.Println("查询失败:", result.Error)
    } else {
        fmt.Println("查询结果:", users)
    }
}

func updateRecord(db *gorm.DB, id int) {
    var user User
    result := db.First(&user, id)
    if result.Error != nil {
        fmt.Println("查询失败:", result.Error)
        return
    }

    user.Email = "new_email@example.com"
    result = db.Save(&user)
    if result.Error != nil {
        fmt.Println("更新失败:", result.Error)
    } else {
        fmt.Println("更新成功")
    }
}

func deleteRecord(db *gorm.DB, id int) {
    var user User
    result := db.First(&user, id)
    if result.Error != nil {
        fmt.Println("查询失败:", result.Error)
        return
    }

    result = db.Delete(&user)
    if result.Error != nil {
        fmt.Println("删除失败:", result.Error)
    } else {
        fmt.Println("删除成功")
    }
}

func main() {
    dsn := "user:password@tcp(host:port)/dbname?charset=utf8mb4&parseTime=True&loc=Local"
    db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
    if err != nil {
        panic("无法连接数据库")
    }
    defer db.Close()

    createRecord(db)
    queryRecords(db)
    updateRecord(db, 1) // 假设有一条ID为1的数据
    deleteRecord(db, 1) // 假设有一条ID为1的数据
}

通过以上代码,我们了解了如何使用GORM连接数据库并实现常见的增、删、改、查操作。在实际开发中,GORM可以大大简化与数据库的交互,提高开发效率。记得根据实际情况修改连接字符串和数据模型定义。