Go 笔记 - Beego 之 orm 增删改查
来源:SegmentFault
2023-02-24 15:42:04
0浏览
收藏
大家好,今天本人给大家带来文章《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`, `<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</nil></nil></nil>执行多次,插入多条测试数据,查看库中数据:
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</null></null></null></null>
删
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</nil>
查看库中数据,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</null>
查
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</nil></nil></nil></nil>改
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</nil></nil></nil>
查苦库中数据,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</null></null>
好了,本文到此结束,带大家了解了《Go 笔记 - Beego 之 orm 增删改查》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多数据库知识!
版本声明
本文转载于:SegmentFault 如有侵犯,请联系study_golang@163.com删除
MySql 非常用语法笔记
- 上一篇
- MySql 非常用语法笔记
- 下一篇
- HeapDump性能社区专题系列四:后端面试必备问题集
查看更多
最新文章
-
- 数据库 · MySQL | 1天前 |
- MySQL数值函数大全及使用技巧
- 117浏览 收藏
-
- 数据库 · MySQL | 2天前 |
- 三种登录MySQL方法详解
- 411浏览 收藏
-
- 数据库 · MySQL | 3天前 |
- MySQL数据备份方法与工具推荐
- 420浏览 收藏
-
- 数据库 · MySQL | 3天前 |
- MySQL数据备份方法与工具推荐
- 264浏览 收藏
-
- 数据库 · MySQL | 4天前 |
- MySQL索引的作用是什么?
- 266浏览 收藏
-
- 数据库 · MySQL | 5天前 |
- MySQL排序原理与实战应用
- 392浏览 收藏
-
- 数据库 · MySQL | 1星期前 |
- MySQLwhere条件查询技巧
- 333浏览 收藏
-
- 数据库 · MySQL | 1星期前 |
- MySQL常用数据类型有哪些?怎么选更合适?
- 234浏览 收藏
-
- 数据库 · MySQL | 1星期前 |
- MySQL常用命令大全管理员必学30条
- 448浏览 收藏
-
- 数据库 · MySQL | 1星期前 |
- MySQL高效批量插入数据方法大全
- 416浏览 收藏
-
- 数据库 · MySQL | 1星期前 |
- MySQL性能优化技巧大全
- 225浏览 收藏
-
- 数据库 · MySQL | 1星期前 |
- MySQL数据备份4种方法保障安全
- 145浏览 收藏
查看更多
课程推荐
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 485次学习
查看更多
AI推荐
-
- ChatExcel酷表
- ChatExcel酷表是由北京大学团队打造的Excel聊天机器人,用自然语言操控表格,简化数据处理,告别繁琐操作,提升工作效率!适用于学生、上班族及政府人员。
- 3163次使用
-
- Any绘本
- 探索Any绘本(anypicturebook.com/zh),一款开源免费的AI绘本创作工具,基于Google Gemini与Flux AI模型,让您轻松创作个性化绘本。适用于家庭、教育、创作等多种场景,零门槛,高自由度,技术透明,本地可控。
- 3375次使用
-
- 可赞AI
- 可赞AI,AI驱动的办公可视化智能工具,助您轻松实现文本与可视化元素高效转化。无论是智能文档生成、多格式文本解析,还是一键生成专业图表、脑图、知识卡片,可赞AI都能让信息处理更清晰高效。覆盖数据汇报、会议纪要、内容营销等全场景,大幅提升办公效率,降低专业门槛,是您提升工作效率的得力助手。
- 3403次使用
-
- 星月写作
- 星月写作是国内首款聚焦中文网络小说创作的AI辅助工具,解决网文作者从构思到变现的全流程痛点。AI扫榜、专属模板、全链路适配,助力新人快速上手,资深作者效率倍增。
- 4506次使用
-
- MagicLight
- MagicLight.ai是全球首款叙事驱动型AI动画视频创作平台,专注于解决从故事想法到完整动画的全流程痛点。它通过自研AI模型,保障角色、风格、场景高度一致性,让零动画经验者也能高效产出专业级叙事内容。广泛适用于独立创作者、动画工作室、教育机构及企业营销,助您轻松实现创意落地与商业化。
- 3784次使用
查看更多
相关文章
-
- golang MySQL实现对数据库表存储获取操作示例
- 2022-12-22 499浏览
-
- 搭建Go语言的ORM框架Gorm的具体步骤(从Java到go)
- 2022-12-30 241浏览
-
- 搞一个自娱自乐的博客(二) 架构搭建
- 2023-02-16 244浏览
-
- B-Tree、B+Tree以及B-link Tree
- 2023-01-19 235浏览
-
- mysql面试题
- 2023-01-17 157浏览

