网站配置域名,免费大数据查询平台,网页个人介绍制作,招聘网站建设与开发要求文章目录 前言1. GORM简介2. 安装GORM并连接MySQL2.1 安装GORM和MySQL驱动2.2 连接MySQL 3. GORM数据模型#xff08;Model#xff09;3.1 定义User结构体3.2 自动迁移#xff08;AutoMigrate#xff09; 4. GORM CRUD 操作4.1 插入数据#xff08;Create#xff09;4.2 … 文章目录 前言1. GORM简介2. 安装GORM并连接MySQL2.1 安装GORM和MySQL驱动2.2 连接MySQL 3. GORM数据模型Model3.1 定义User结构体3.2 自动迁移AutoMigrate 4. GORM CRUD 操作4.1 插入数据Create4.2 查询数据Read4.3 更新数据Update4.4 删除数据Delete 5. 进阶功能事务 关联关系5.1 事务操作 6. GORM 性能优化6.1 添加索引6.2 批量插入 总结 前言
✅ 适合人群Go 后端开发者 | 数据库开发者 | 想掌握 GORM 的工程师 ✅ 文章亮点从 安装、基础操作、CRUD、事务、索引优化 到 进阶技巧全面解析 GORM ✅ 目标掌握 Go 语言 MySQLGORM开发高效数据库应用
1. GORM简介
GORM是Go语言最流行的ORM框架它提供了一套强大且简介的数据库操作API相比database/sql它具备以下优势 ✅ 代码简洁无需手写 SQL使用链式调用 ✅ 支持自动迁移可自动创建和更新数据库表结构 ✅ 支持事务、预加载、钩子函数 ✅ 支持多种数据库MySQL、PostgreSQL、SQLite、SQL Server ✅ 支持软删除、乐观锁、索引管理
2. 安装GORM并连接MySQL
2.1 安装GORM和MySQL驱动
执行以下命令安装 GORM 和 MySQL 依赖
go get -u gorm.io/gorm
go get -u gorm.io/driver/mysql2.2 连接MySQL
在main.go中编写数据库连接代码
package mainimport (fmtgorm.io/driver/mysqlgorm.io/gorm
)
var DB *gorm.DB // 全局数据库实例func InitDB() {dsn : root:passwordtcp(127.0.0.1:3306)/testdb?charsetutf8mb4parseTimeTruelocLocalvar err errorDB, err gorm.Open(mysql.Open(dsn), gorm.Config{})if err ! nil {panic(数据库连接失败 err.Error())}fmt.Println(数据库连接成功)
}func main() {InitDB()
}替换 root:password 为你的 MySQL 账号密码testdb 为数据库名称 确保 MySQL 服务已开启并且testdb数据库已存在
3. GORM数据模型Model
GORM的模型Model类似于数据库中的表每个字段对应表的列。
3.1 定义User结构体
type User struct {ID uint gorm:primaryKey // 主键Name string gorm:size:100 // 名字最大100字符Age int // 年龄Email string gorm:unique // 邮箱唯一约束CreateAt time.Time
}3.2 自动迁移AutoMigrate
GORM支持自动迁移可以自动创建表结构。
package mainimport (fmttimegorm.io/driver/mysqlgorm.io/gorm
)type User struct {ID uint gorm:primaryKey // 主键Name string gorm:size:100 // 名字最大100字符Age int // 年龄Email string gorm:unique // 邮箱唯一约束CreateAt time.Time
}var DB *gorm.DBfunc InitDB() {dsn : root:passwordtcp(127.0.0.1:3306)/testdb?charsetutf8mb4parseTimeTruelocLocalvar err errorDB, err gorm.Open(mysql.Open(dsn), gorm.Config{})if err ! nil {panic(❌ 数据库连接失败 err.Error())}fmt.Println(✅ 数据库连接成功)
}func Migrate() {err : DB.AutoMigrate(User{}) // 自动迁移User表if err ! nil {fmt.Println(数据库迁移失败, err)}else {fmt.Println(数据库迁移成功)}
}func main() {InitDB()Migrate()
}运行 go run main.go会自动创建 users 表
4. GORM CRUD 操作
4.1 插入数据Create
package mainimport (fmttimegorm.io/driver/mysqlgorm.io/gorm
)type User struct {ID uint gorm:primaryKey // 主键Name string gorm:size:100 // 名字最大100字符Age int // 年龄Email string gorm:unique // 邮箱唯一约束CreateAt time.Time
}var DB *gorm.DBfunc InitDB() {dsn : root:123456tcp(127.0.0.1:3306)/testdb?charsetutf8mb4parseTimeTruelocLocalvar err errorDB, err gorm.Open(mysql.Open(dsn), gorm.Config{})if err ! nil {panic(❌ 数据库连接失败 err.Error())}fmt.Println(✅ 数据库连接成功)
}func Migrate() {err : DB.AutoMigrate(User{}) // 自动迁移User表if err ! nil {fmt.Println(数据库迁移失败, err)} else {fmt.Println(数据库迁移成功)}
}func CreateUser() {user : User{Name: Zhangsan, Age: 18, Email: ponymatencent.com,CreateAt: time.Now()}result : DB.Create(user)if result.Error ! nil {fmt.Println(数据插入失败, result.Error)} else {fmt.Println(数据插入成功, user)}
}func main() {InitDB()// Migrate()CreateUser()}4.2 查询数据Read
func GetUserByID(id int) {var user Userresult : DB.First(user, id)if result.Error ! nil {fmt.Println(查询失败,result.Error)}else {fmt.Println(查询成功,user)}
}4.3 更新数据Update
func UpdateUser(id int,newAge int) {result :DB.Model(User{}).Where(id ?,id).Update(age,newAge)if result.Error ! nil {fmt.Println(数据更新失败, result.Error)}else {fmt.Println(数据更新成功, result.RowsAffected,行)}
}4.4 删除数据Delete
func DeleteUser(id uint) {result : DB.Delete(User{}, id)if result.Error ! nil {fmt.Println(❌ 删除失败:, result.Error)} else {fmt.Println(✅ 删除成功:, result.RowsAffected, 行)}
}5. 进阶功能事务 关联关系
5.1 事务操作
func TransferFunds(senderID, receiverID uint, amount int) {tx : DB.Begin() // 开启事务defer func() {if r : recover(); r ! nil {tx.Rollback() // 事务回滚}}()sender : User{}receiver : User{}if err : tx.First(sender, senderID).Error; err ! nil {tx.Rollback()return}if err : tx.First(receiver, receiverID).Error; err ! nil {tx.Rollback()return}// 模拟扣款sender.Age - amountreceiver.Age amountif err : tx.Save(sender).Error; err ! nil {tx.Rollback()return}if err : tx.Save(receiver).Error; err ! nil {tx.Rollback()return}tx.Commit() // 提交事务
}
6. GORM 性能优化
6.1 添加索引
type Product struct {ID uint gorm:primaryKeyName string gorm:index // 索引Price float64
}6.2 批量插入
func BatchInsertUsers(users []User) {DB.Create(users)
}总结
✅ 学习了 GORM 基础安装、连接 MySQL、定义 Model ✅ 掌握了 CRUD 操作插入、查询、更新、删除 ✅ 实现了事务操作防止数据不一致 ✅ 了解了索引优化 性能优化 现在你已经掌握了 Go MySQLGORM的完整开发流程 文章转载自: http://www.morning.kjrlp.cn.gov.cn.kjrlp.cn http://www.morning.nxfwf.cn.gov.cn.nxfwf.cn http://www.morning.ktlfb.cn.gov.cn.ktlfb.cn http://www.morning.xq3nk42mvv.cn.gov.cn.xq3nk42mvv.cn http://www.morning.qdcpn.cn.gov.cn.qdcpn.cn http://www.morning.tqsgt.cn.gov.cn.tqsgt.cn http://www.morning.jpkhn.cn.gov.cn.jpkhn.cn http://www.morning.hsjfs.cn.gov.cn.hsjfs.cn http://www.morning.tmlhh.cn.gov.cn.tmlhh.cn http://www.morning.kflbf.cn.gov.cn.kflbf.cn http://www.morning.ccjhr.cn.gov.cn.ccjhr.cn http://www.morning.drywd.cn.gov.cn.drywd.cn http://www.morning.dsncg.cn.gov.cn.dsncg.cn http://www.morning.pwghp.cn.gov.cn.pwghp.cn http://www.morning.yrmpz.cn.gov.cn.yrmpz.cn http://www.morning.zpdjh.cn.gov.cn.zpdjh.cn http://www.morning.xnkb.cn.gov.cn.xnkb.cn http://www.morning.iknty.cn.gov.cn.iknty.cn http://www.morning.dangaw.com.gov.cn.dangaw.com http://www.morning.cniedu.com.gov.cn.cniedu.com http://www.morning.lrybz.cn.gov.cn.lrybz.cn http://www.morning.zffps.cn.gov.cn.zffps.cn http://www.morning.nrbcx.cn.gov.cn.nrbcx.cn http://www.morning.jlxqx.cn.gov.cn.jlxqx.cn http://www.morning.rjnky.cn.gov.cn.rjnky.cn http://www.morning.wyrkp.cn.gov.cn.wyrkp.cn http://www.morning.qkpzq.cn.gov.cn.qkpzq.cn http://www.morning.wqpsf.cn.gov.cn.wqpsf.cn http://www.morning.xfjwm.cn.gov.cn.xfjwm.cn http://www.morning.spfq.cn.gov.cn.spfq.cn http://www.morning.bttph.cn.gov.cn.bttph.cn http://www.morning.rkfxc.cn.gov.cn.rkfxc.cn http://www.morning.brwp.cn.gov.cn.brwp.cn http://www.morning.bpwfr.cn.gov.cn.bpwfr.cn http://www.morning.dmwck.cn.gov.cn.dmwck.cn http://www.morning.swsrb.cn.gov.cn.swsrb.cn http://www.morning.rsbqq.cn.gov.cn.rsbqq.cn http://www.morning.wncb.cn.gov.cn.wncb.cn http://www.morning.llxns.cn.gov.cn.llxns.cn http://www.morning.bswhr.cn.gov.cn.bswhr.cn http://www.morning.kgqww.cn.gov.cn.kgqww.cn http://www.morning.fhyhr.cn.gov.cn.fhyhr.cn http://www.morning.sloxdub.cn.gov.cn.sloxdub.cn http://www.morning.tdttz.cn.gov.cn.tdttz.cn http://www.morning.lpqgq.cn.gov.cn.lpqgq.cn http://www.morning.wtrjq.cn.gov.cn.wtrjq.cn http://www.morning.ykwgl.cn.gov.cn.ykwgl.cn http://www.morning.tbkqs.cn.gov.cn.tbkqs.cn http://www.morning.dmzfz.cn.gov.cn.dmzfz.cn http://www.morning.nlywq.cn.gov.cn.nlywq.cn http://www.morning.rwtlj.cn.gov.cn.rwtlj.cn http://www.morning.ahlart.com.gov.cn.ahlart.com http://www.morning.tsmxh.cn.gov.cn.tsmxh.cn http://www.morning.nkiqixr.cn.gov.cn.nkiqixr.cn http://www.morning.nrftd.cn.gov.cn.nrftd.cn http://www.morning.lffgs.cn.gov.cn.lffgs.cn http://www.morning.xmttd.cn.gov.cn.xmttd.cn http://www.morning.ryxbz.cn.gov.cn.ryxbz.cn http://www.morning.zgnng.cn.gov.cn.zgnng.cn http://www.morning.mfbzr.cn.gov.cn.mfbzr.cn http://www.morning.spsqr.cn.gov.cn.spsqr.cn http://www.morning.pntzg.cn.gov.cn.pntzg.cn http://www.morning.rhfh.cn.gov.cn.rhfh.cn http://www.morning.cmqrg.cn.gov.cn.cmqrg.cn http://www.morning.mmosan.com.gov.cn.mmosan.com http://www.morning.qznkn.cn.gov.cn.qznkn.cn http://www.morning.lqjpb.cn.gov.cn.lqjpb.cn http://www.morning.gnbfj.cn.gov.cn.gnbfj.cn http://www.morning.mlzyx.cn.gov.cn.mlzyx.cn http://www.morning.nlnmy.cn.gov.cn.nlnmy.cn http://www.morning.ryzgp.cn.gov.cn.ryzgp.cn http://www.morning.bxrlt.cn.gov.cn.bxrlt.cn http://www.morning.jqpq.cn.gov.cn.jqpq.cn http://www.morning.ltpmy.cn.gov.cn.ltpmy.cn http://www.morning.bpwz.cn.gov.cn.bpwz.cn http://www.morning.rzbgn.cn.gov.cn.rzbgn.cn http://www.morning.jfwrf.cn.gov.cn.jfwrf.cn http://www.morning.yxnkr.cn.gov.cn.yxnkr.cn http://www.morning.cwgn.cn.gov.cn.cwgn.cn http://www.morning.qbwyd.cn.gov.cn.qbwyd.cn