关于beego:Go-笔记-Beego-之-orm-增删改查

48次阅读

共计 9877 个字符,预计需要花费 25 分钟才能阅读完成。

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`, `<nil>`, ``, `false`
3 <nil> {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 <nil>  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 | <null>     |             | 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 | <null>     |             | 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 | <null>     |             | 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 | <null>     |             | 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 <nil>

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 | <null>     |             | 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`
<nil> &{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 <nil>  false}
[ORM]2022/03/21 17:16:17  -[Queries/default] - [OK / db.QueryRow /     0.0ms] - [SELECT COUNT(*) FROM `account` T0 ]
1 <nil>
[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 <nil>  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`, ``, `<nil>`, ``, ``, ` 中国北京 `, `0`, `0`, `0`, `2022-03-21 17:29:09.6174111 +0800 CST`, `<nil>`, ``, `false`, `1`
<nil> 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  |          | <null>   |           |       | 中国北京 | 0      | 0       | 0             | 2022-03-21 09:06:32 | 2022-03-21 09:29:09 | <null>     |             | 0   |
+-----+------+----------+----------+-----------+-------+----------+--------+---------+---------------+---------------------+---------------------+------------+-------------+-----+

1 row in set
Time: 0.005s

正文完
 0