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 非常用语法笔记

- 下一篇
- HeapDump性能社区专题系列四:后端面试必备问题集
查看更多
最新文章
-
- 数据库 · MySQL | 14小时前 |
- 主外键关系怎么建立?
- 149浏览 收藏
-
- 数据库 · MySQL | 15小时前 |
- MySQL中IF函数使用详解
- 392浏览 收藏
-
- 数据库 · MySQL | 1天前 |
- MySQL中IF函数使用详解
- 268浏览 收藏
-
- 数据库 · MySQL | 1天前 |
- MySQL入门:核心概念与操作全解析
- 162浏览 收藏
-
- 数据库 · MySQL | 1天前 |
- MySQL事务是什么?如何保证数据一致性?
- 349浏览 收藏
-
- 数据库 · MySQL | 2天前 |
- MySQL数据分片实现方法及常见方案解析
- 363浏览 收藏
-
- 数据库 · MySQL | 2天前 |
- MySQL基础:增删改查全教程
- 345浏览 收藏
-
- 数据库 · MySQL | 3天前 |
- 5种方法检测电脑是否安装MySQL
- 275浏览 收藏
-
- 数据库 · MySQL | 4天前 |
- 主键与唯一键区别详解,如何正确选择主键
- 271浏览 收藏
-
- 数据库 · MySQL | 4天前 |
- MySQL创建数据库的详细步骤教程
- 262浏览 收藏
-
- 数据库 · MySQL | 4天前 |
- MySQL建表完整命令行操作步骤
- 389浏览 收藏
-
- 数据库 · MySQL | 1星期前 |
- MySQL中HAVING和WHERE的区别
- 203浏览 收藏
查看更多
课程推荐
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 514次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 499次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 484次学习
查看更多
AI推荐
-
- AI Mermaid流程图
- SEO AI Mermaid 流程图工具:基于 Mermaid 语法,AI 辅助,自然语言生成流程图,提升可视化创作效率,适用于开发者、产品经理、教育工作者。
- 485次使用
-
- 搜获客【笔记生成器】
- 搜获客笔记生成器,国内首个聚焦小红书医美垂类的AI文案工具。1500万爆款文案库,行业专属算法,助您高效创作合规、引流的医美笔记,提升运营效率,引爆小红书流量!
- 479次使用
-
- iTerms
- iTerms是一款专业的一站式法律AI工作台,提供AI合同审查、AI合同起草及AI法律问答服务。通过智能问答、深度思考与联网检索,助您高效检索法律法规与司法判例,告别传统模板,实现合同一键起草与在线编辑,大幅提升法律事务处理效率。
- 507次使用
-
- TokenPony
- TokenPony是讯盟科技旗下的AI大模型聚合API平台。通过统一接口接入DeepSeek、Kimi、Qwen等主流模型,支持1024K超长上下文,实现零配置、免部署、极速响应与高性价比的AI应用开发,助力专业用户轻松构建智能服务。
- 545次使用
-
- 迅捷AIPPT
- 迅捷AIPPT是一款高效AI智能PPT生成软件,一键智能生成精美演示文稿。内置海量专业模板、多样风格,支持自定义大纲,助您轻松制作高质量PPT,大幅节省时间。
- 476次使用
查看更多
相关文章
-
- 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浏览