go gorm 操作MySQL初探

  1. 安装
bash 复制代码
go get -u gorm.io/gen
  1. 实例
bash 复制代码
package main

import (
	"fmt"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

type Product struct {
	gorm.Model
	Name  string
	Price float64
}

func main() {
	// 其中loc是为了解决时间类型timezone少8小时
	dsn := "ellis:ellis@tcp(192.168.214.134:3306)/go_db?charset=utf8mb4&parseTime=True&loc=Local"

	d, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic(err)
	}

	d.AutoMigrate(&Product{})

	// d.Create(&Product{Name: "haha", Price: 120.09})

	var product Product
	// 根据ID查询
	d.First(&product, 1)
	// 根据name查询
	d.First(&product, "name=?", "haha")
	fmt.Printf("product.Price: %v\n", product.Price)
	// update一个字段
	d.Model(&product).Update("Price", 190)

	// 更新多个字段
	d.Model(&product).Updates(Product{Name: "11", Price: 120})
	d.Model(&product).Updates(map[string]interface{}{"Price": 199})
}
	//软删除,更新deleted_at字段
	d.Where("name=?", "11").Delete(&Product{})
	//硬删除
	d.Where("name=?", "11").Unscoped().Delete(&Product{})

参考
https://duoke360.com/tutorial/gorm/query-recored

相关推荐
于眠牧北1 天前
MySQL的锁类型,表锁,行锁,MVCC中所使用的临键锁
mysql
Turnip12023 天前
深度解析:为什么简单的数据库"写操作"会在 MySQL 中卡住?
后端·mysql
花酒锄作田4 天前
Gin 框架中的规范响应格式设计与实现
golang·gin
加号34 天前
windows系统下mysql多源数据库同步部署
数据库·windows·mysql
シ風箏4 天前
MySQL【部署 04】Docker部署 MySQL8.0.32 版本(网盘镜像及启动命令分享)
数据库·mysql·docker
WeiXin_DZbishe4 天前
基于django在线音乐数据采集的设计与实现-计算机毕设 附源码 22647
javascript·spring boot·mysql·django·node.js·php·html5
爱可生开源社区4 天前
MySQL 性能优化:真正重要的变量
数据库·mysql
小马爱打代码4 天前
MySQL性能优化核心:InnoDB Buffer Pool 详解
数据库·mysql·性能优化
风流 少年4 天前
mysql mcp
数据库·mysql·adb
西门吹雪分身4 天前
mysql之数据离线迁移
数据库·mysql