登录
首页 >  数据库 >  MySQL

Go 笔记 - Beego 之 orm 增删改查

来源:SegmentFault

时间:2023-02-24 15:42:04 433浏览 收藏

大家好,今天本人给大家带来文章《Go 笔记 - Beego 之 orm 增删改查》,文中内容主要涉及到MySQL、gorm、beego,如果你对数据库方面的知识点感兴趣,那就请各位朋友继续看下去吧~希望能真正帮到你们,谢谢!

package main

import (
    "fmt"
    "github.com/beego/beego/v2/client/orm"
    _ "github.com/go-sql-driver/mysql"
    "log"
    "time"
)

type Account struct {
    ID           int64
    Name         string
    Password     string
    Birthday     *time.Time
    Telephone    string
    Email        string
    Addr         string
    Status       int8
    RoleId       int64
    DepartmentId int64
    CreatedAt    *time.Time `orm:"auto_now_add"`
    UpdatedAt    *time.Time `orm:"auto_now"`
    //DeletedAt    *time.Time `orm:"null"`
    DeletedAt   *time.Time
    Description string
    Sex         bool
}

func main() {
    orm.Debug = true // 打印 sql 。可能影响性能。生产不建议使用
    
    driverName := "mysql" // 驱动名

    databaseName := "default"

    dsn := "golang:123456@tcp(192.168.100.20:33060)/cmdb?charset=utf8mb4&parseTime=true"
    
    // 注册数据库驱动到 orm
    // 参数:自定义的数据库类型名,驱动类型(orm 中提供的)
    orm.RegisterDriver(driverName, orm.DRMySQL)

    // 参数:beego 必须指定默认的数据库名称,使用的驱动名称(orm 驱动类型名),数据库的配置信息,数据库(连接池),连接(池)名称
    err := orm.RegisterDataBase(databaseName, driverName, dsn)
    if err != nil {
        log.Fatal(err)
    }

    // 定义结构
    // 注册模型
    orm.RegisterModel(new(Account))

    now := time.Now()
    // 增
    // 先创建一个 orm 对象
    ormer := orm.NewOrm()

    account := Account{
        Name:      "dangdang",
        Password:  "123456",
        Birthday:  &now, // 需要使用指针,所以前面需要先定义个 now 变量
        Telephone: "88888888",
        Email:     "aaa@126.com",
    }

    id, err := ormer.Insert(&account)
    fmt.Println(id, err, account)
}

执行过程如下:

[ORM]2022/03/21 16:19:26  -[Queries/default] - [  OK /     db.Exec /     0.9ms] - [INSERT INTO `account` (`name`, `password`, `birthday`, `telephone`, `email`, `addr`, `status`, `role_id`, `department_id`, `created_at`, `updated_at`, `deleted_at`, `description`, `sex`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)] - `xyz`, `123456`, `2022-03-21 16:19:26.4459767 +0800 CST m=+0.026482301`, `666666`, `aaa@126.com`, ``, `0`, `0`, `0`, `2022-03-21 16:19:26.4466412 +0800 CST`, `2022-03-21 16:19:26.4466412 +0800 CST`, ``, ``, `false`
3  {3 xyz 123456 2022-03-21 16:19:26.4459767 +0800 CST m=+0.026482301 666666 aaa@126.com  0 0 0 2022-03-21 16:19:26.4466412 +0800 CST 2022-03-21 16:19:26.4466412 +0800 CST   false}

Process finished with exit code 0

执行多次,插入多条测试数据,查看库中数据:

MariaDB root@localhost:cmdb> select * from account;
+-----+----------+----------+---------------------+-----------+-------------+------+--------+---------+---------------+---------------------+---------------------+------------+-------------+-----+
| i_d | name     | password | birthday            | telephone | email       | addr | status | role_id | department_id | created_at          | updated_at          | deleted_at | description | sex |
+-----+----------+----------+---------------------+-----------+-------------+------+--------+---------+---------------+---------------------+---------------------+------------+-------------+-----+
| 1   | dangdang | 123456   | 2022-03-21 08:13:03 | 88888888  | aaa@126.com |      | 0      | 0       | 0             | 2022-03-21 08:13:03 | 2022-03-21 08:13:03 |      |             | 0   |
| 2   | abc      | 123456   | 2022-03-21 08:19:06 | 88888888  | aaa@126.com |      | 0      | 0       | 0             | 2022-03-21 08:19:06 | 2022-03-21 08:19:06 |      |             | 0   |
| 3   | xyz      | 123456   | 2022-03-21 08:19:26 | 666666    | aaa@126.com |      | 0      | 0       | 0             | 2022-03-21 08:19:26 | 2022-03-21 08:19:26 |      |             | 0   |
| 4   | xyz      | 123456   | 2022-03-21 08:39:54 | 999999    | xyz@126.com |      | 0      | 0       | 0             | 2022-03-21 08:39:54 | 2022-03-21 08:39:54 |      |             | 0   |
+-----+----------+----------+---------------------+-----------+-------------+------+--------+---------+---------------+---------------------+---------------------+------------+-------------+-----+

4 rows in set
Time: 0.006s

package main

import (
    "fmt"
    "github.com/beego/beego/v2/client/orm"
    _ "github.com/go-sql-driver/mysql"
    "log"
    "time"
)

type Account struct {
    ID           int64
    Name         string
    Password     string
    Birthday     *time.Time
    Telephone    string
    Email        string
    Addr         string
    Status       int8
    RoleId       int64
    DepartmentId int64
    CreatedAt    *time.Time `orm:"auto_now_add"`
    UpdatedAt    *time.Time `orm:"auto_now"`
    //DeletedAt    *time.Time `orm:"null"`
    DeletedAt   *time.Time
    Description string
    Sex         bool
}

func main() {
    orm.Debug = true // 打印 sql 。可能影响性能。生产不建议使用
    // 驱动名
    driverName := "mysql"
    //
    databaseName := "default"

    dsn := "golang:123456@tcp(192.168.100.20:33060)/cmdb?charset=utf8mb4&parseTime=true"
    // 注册数据库驱动到 orm
    // 参数:自定义的数据库类型名,驱动类型(orm 中提供的)
    orm.RegisterDriver(driverName, orm.DRMySQL)

    // 参数:beego 必须指定默认的数据库名称,使用的驱动名称(orm 驱动类型名),数据库的配置信息,数据库(连接池),连接(池)名称
    err := orm.RegisterDataBase(databaseName, driverName, dsn)
    if err != nil {
        log.Fatal(err)
    }

    // 定义结构
    // 注册模型
    orm.RegisterModel(new(Account))

    // 先创建一个 orm 对象
    ormer := orm.NewOrm()

    // 删
    // 如果 ormer.Delete() 中不指定字段,默认只会根据 orm 识别出来的主键去删除,即示例中的 Name: "dangdang" 其实没什么用,其实是按照 ID 在删除。在代码执行过程能看出来。
    deleteAccount := &Account{ID: 1, Name: "dangdang"}
    id, err := ormer.Delete(deleteAccount)

    // 如果要使用非主键删除,需要在 ormer.Delete() 中指定字段名。另外,以 Name 为例,如果表中有多条数据的 Name 值相同,则会全部删除
    deleteAccount = &Account{Name: "xyz"}
    id, err = ormer.Delete(deleteAccount, "Name")
    fmt.Println(id, err)
}

执行过程如下:

[ORM]2022/03/21 16:41:04  -[Queries/default] - [  OK /     db.Exec /     1.4ms] - [DELETE FROM `account` WHERE `i_d` = ?] - `1`
[ORM]2022/03/21 16:41:04  -[Queries/default] - [  OK /     db.Exec /     1.0ms] - [DELETE FROM `account` WHERE `name` = ?] - `xyz`
2 

Process finished with exit code 0

查看库中数据,Name 为 xyz 的两条数据都被删除了:

MariaDB root@localhost:cmdb> select * from account;
+-----+------+----------+---------------------+-----------+-------------+------+--------+---------+---------------+---------------------+---------------------+------------+-------------+-----+
| i_d | name | password | birthday            | telephone | email       | addr | status | role_id | department_id | created_at          | updated_at          | deleted_at | description | sex |
+-----+------+----------+---------------------+-----------+-------------+------+--------+---------+---------------+---------------------+---------------------+------------+-------------+-----+
| 2   | abc  | 123456   | 2022-03-21 08:19:06 | 88888888  | aaa@126.com |      | 0      | 0       | 0             | 2022-03-21 08:19:06 | 2022-03-21 08:19:06 |      |             | 0   |
+-----+------+----------+---------------------+-----------+-------------+------+--------+---------+---------------+---------------------+---------------------+------------+-------------+-----+

1 row in set
Time: 0.005s

package main

import (
    "fmt"
    "github.com/beego/beego/v2/client/orm"
    _ "github.com/go-sql-driver/mysql"
    "log"
    "time"
)

type Account struct {
    ID           int64
    Name         string
    Password     string
    Birthday     *time.Time
    Telephone    string
    Email        string
    Addr         string
    Status       int8
    RoleId       int64
    DepartmentId int64
    CreatedAt    *time.Time `orm:"auto_now_add"`
    UpdatedAt    *time.Time `orm:"auto_now"`
    //DeletedAt    *time.Time `orm:"null"`
    DeletedAt   *time.Time
    Description string
    Sex         bool
}

func main() {
    orm.Debug = true // 打印 sql 。可能影响性能。生产不建议使用
    // 驱动名
    driverName := "mysql"
    //
    databaseName := "default"

    dsn := "golang:123456@tcp(192.168.100.20:33060)/cmdb?charset=utf8mb4&parseTime=true"
    // 注册数据库驱动到 orm
    // 参数:自定义的数据库类型名,驱动类型(orm 中提供的)
    orm.RegisterDriver(driverName, orm.DRMySQL)

    // 参数:beego 必须指定默认的数据库名称,使用的驱动名称(orm 驱动类型名),数据库的配置信息,数据库(连接池),连接(池)名称
    err := orm.RegisterDataBase(databaseName, driverName, dsn)
    if err != nil {
        log.Fatal(err)
    }

    // 定义结构
    // 注册模型
    orm.RegisterModel(new(Account))

    // 先创建一个 orm 对象
    ormer := orm.NewOrm()

    // 查
    // 查一个结果
    accountDetail := &Account{Name: "abc"}
    err = ormer.Read(accountDetail, "Name") // 类似删除。默认也是通多主键查询。如果要使用非主键查询,需要指定。不同于删除功能的是,查到第一条符合预期的数据后,查询就结束了,不会把所有符合条件的数据都查出来
    fmt.Println(err, accountDetail)

    // 查询列表 QueryTable
    queryset := ormer.QueryTable(new(Account))
    fmt.Println(queryset.Count())
    accounts := make([]Account, 0) // 创建一个切片用于存放用户信息
    queryset.All(&accounts)
    fmt.Println(accounts)
}

执行过程如下:

[ORM]2022/03/21 17:16:17  -[Queries/default] - [  OK / db.QueryRow /     0.9ms] - [SELECT `i_d`, `name`, `password`, `birthday`, `telephone`, `email`, `addr`, `status`, `role_id`, `department_id`, `created_at`, `updated_at`, `deleted_at`, `description`, `sex` FROM `account` WHERE `name` = ? ] - `abc`
 &{1 abc 123456 2022-03-21 17:06:32 +0800 CST 88888888 abc@126.com  0 0 0 2022-03-21 17:06:32 +0800 CST 2022-03-21 17:09:55 +0800 CST   false}
[ORM]2022/03/21 17:16:17  -[Queries/default] - [  OK / db.QueryRow /     0.0ms] - [SELECT COUNT(*) FROM `account` T0 ]
1 
[ORM]2022/03/21 17:16:17  -[Queries/default] - [  OK /    db.Query /     0.5ms] - [SELECT T0.`i_d`, T0.`name`, T0.`password`, T0.`birthday`, T0.`telephone`, T0.`email`, T0.`addr`, T0.`status`, T0.`role_id`, T0.`department_id`, T0.`created_at`, T0.`updated_at`, T0.`deleted_at`, T0.`description`, T0.`sex` FROM `account` T0 ]
[{1 abc 123456 2022-03-21 17:06:32 +0800 CST 88888888 abc@126.com  0 0 0 2022-03-21 17:06:32 +0800 CST 2022-03-21 17:09:55 +0800 CST   false}]

Process finished with exit code 0

package main

import (
    "fmt"
    "github.com/beego/beego/v2/client/orm"
    _ "github.com/go-sql-driver/mysql"
    "log"
    "time"
)

type Account struct {
    ID           int64
    Name         string
    Password     string
    Birthday     *time.Time `orm:"null"`
    Telephone    string
    Email        string
    Addr         string
    Status       int8
    RoleId       int64
    DepartmentId int64
    CreatedAt    *time.Time `orm:"auto_now_add"`
    UpdatedAt    *time.Time `orm:"auto_now"`
    //DeletedAt    *time.Time `orm:"null"`
    DeletedAt   *time.Time
    Description string
    Sex         bool
}

func main() {
    orm.Debug = true // 打印 sql 。可能影响性能。生产不建议使用
    // 驱动名
    driverName := "mysql"
    //
    databaseName := "default"

    dsn := "golang:123456@tcp(192.168.100.20:33060)/cmdb?charset=utf8mb4&parseTime=true"
    // 注册数据库驱动到 orm
    // 参数:自定义的数据库类型名,驱动类型(orm 中提供的)
    orm.RegisterDriver(driverName, orm.DRMySQL)

    // 参数:beego 必须指定默认的数据库名称,使用的驱动名称(orm 驱动类型名),数据库的配置信息,数据库(连接池),连接(池)名称
    err := orm.RegisterDataBase(databaseName, driverName, dsn)
    if err != nil {
        log.Fatal(err)
    }

    // 定义结构
    // 注册模型
    orm.RegisterModel(new(Account))

    // 先创建一个 orm 对象
    ormer := orm.NewOrm()

    // 改
    accountDetail := &Account{Name: "abc", ID: 1}
    //err = ormer.Read(accountDetail, "Name")
    //fmt.Println(err, accountDetail)

    accountDetail.Addr = "中国北京"
    id, err := ormer.Update(accountDetail) // 类似 ormer.Read(),匹配到多条数据时,只更新第一条
    fmt.Println(err, id)
}

执行过程如下:

[ORM]2022/03/21 17:29:09  -[Queries/default] - [  OK /     db.Exec /     1.7ms] - [UPDATE `account` SET `name` = ?, `password` = ?, `birthday` = ?, `telephone` = ?, `email` = ?, `addr` = ?, `status` = ?, `role_id` = ?, `department_id` = ?, `updated_at` = ?, `deleted_at` = ?, `description` = ?, `sex` = ? WHERE `i_d` = ?] - `abc`, ``, ``, ``, ``, `中国北京`, `0`, `0`, `0`, `2022-03-21 17:29:09.6174111 +0800 CST`, ``, ``, `false`, `1`
 1

Process finished with exit code 0

查苦库中数据,Addr 已变更:

MariaDB root@localhost:cmdb> select * from account;
+-----+------+----------+----------+-----------+-------+----------+--------+---------+---------------+---------------------+---------------------+------------+-------------+-----+
| i_d | name | password | birthday | telephone | email | addr     | status | role_id | department_id | created_at          | updated_at          | deleted_at | description | sex |
+-----+------+----------+----------+-----------+-------+----------+--------+---------+---------------+---------------------+---------------------+------------+-------------+-----+
| 1   | abc  |          |    |           |       | 中国北京 | 0      | 0       | 0             | 2022-03-21 09:06:32 | 2022-03-21 09:29:09 |      |             | 0   |
+-----+------+----------+----------+-----------+-------+----------+--------+---------+---------------+---------------------+---------------------+------------+-------------+-----+

1 row in set
Time: 0.005s

好了,本文到此结束,带大家了解了《Go 笔记 - Beego 之 orm 增删改查》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多数据库知识!

声明:本文转载于:SegmentFault 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>