golang快速入门—gorm数据库 *** 作

golang快速入门—gorm数据库 *** 作,第1张

概述 GORM是Golang目前比较热门的数据库ORM *** 作库,对开发者也比较友好,使用非常方便简单,使用上主要就是把struct类型和数据库表记录进行映射, *** 作数据库的时候不需要直接手写Sql代码GORM库github地址: https://github.com/go-gorm/gorm关系型数据库都可适用(mysql/sqlite3/postgresql等) 依赖安装 gorm
go get -u gorm.io/gorm
mysql
如果你使用mysql
go get -u gorm.io/driver/mysql
数据库实 *** 初始化数据库
package test_gorm

import (
	"gorm.io/gorm"
	_ "gorm.io/gorm/dialects/sqlite"
)

var db *gorm.DB

func init() {
	var err error
	db, err = gorm.Open("sqlite3", "test.db") // 连接数据库sqlite3
	db = db.Debug() // 设置数据库模式,这样方便输出日志以及sql原句
	if err != nil {
		panic(err)
	}
	sqlDB := db.DB() 
	sqlDB.SetMaxOpenConns(100) // 设置连接池最大连接数
	sqlDB.SetMaxIdleConns(20) // 设置空闲连接数
}

// 全局获取,给其他模块适用
func GetDB() *gorm.DB {
	return db
}

建立数据库模型
package test_gorm

import "gorm.io/gorm"

/*
CREATE TABLE `food` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增ID,商品Id',
`name` varchar(30) NOT NULL COMMENT '商品名',
`price` decimal(10,2) unsigned  NOT NULL COMMENT '商品价格',
`type_id` int(10) unsigned NOT NULL COMMENT '商品类型Id',
`createtime` int(10) NOT NULL DEFAULT 0 COMMENT '创建时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
*/ 

// 定义表数据库表结构
type Food struct {
	gorm.Model // gorm内置了几个常用字段
	Name   string
	Price  float64
	TypeId int
}

插入数据
package test_gorm

import (
	"fmt"
)

func CreateFood() {
	db.Create(&Food{
		Price:  10.3,
		Name:   "ljc",
		TypeId: 1,
	})
	fmt.Println("成功创建")
}
查询数据
package test_gorm

import (
	"fmt"
)


func FirstFood() {
	food := Food{}
	db.First(&food) // 获取第一条数据
	fmt.Println("FirstFood-->", food)
}

func TakeFood() {
	food := Food{}
	db.Take(&food) // 获取一条数据,此时数据库表为food
	fmt.Println("TakeFood-->", food)
}

func ModelTake() {
	food := Food{}
	db.Model(Food{}).Take(&food) // 获取一条数据,此时数据库表由Mode指定
	fmt.Println("ModelTake-->", food)
}

func LastFood() {
	food := Food{}
	db.Last(&food) // 获取最后一条数据
	fmt.Println("LastFood-->", food)
}

func FindFood(limit int) {
	var foods []Food
	db.Limit(limit).Find(&foods) // 获取多条数据,列表
	for index, food_ := range foods {
		fmt.Println("FindFood-->", index, food_)
	}
}

func Where() {
	food := Food{}
	db.Where("id == ?", 3).Take(&food) // 条件查询,sql
	fmt.Println("Where-->", food)
	food_ := Food{}
	food_.ID = 5
	db.Where(&food_).Take(&food_) // 条件查询,结构体
	fmt.Println("Where-->", food_)

}

func Select() {
	food := Food{}
	db.Model(food).Where("id == ?", 3).Select("name").Take(&food) // 筛选字段
	fmt.Println("Select-->", food)
}

func Count() {
	var total int
	db.Model(Food{}).Count(&total) // 计数
	fmt.Println("Count-->", total)
}

更新数据
package test_gorm

import "fmt"

func WhereSave() {
	food := Food{}
	db.Model(food).Where("id == ?", 3).Take(&food)
	food.Name = "ljc"
	db.Save(&food) // 修改数据后直接save
	fmt.Println("WhereSaveBefore-->", food)
	food.Name = "jacklee"
	db.Save(&food)
	fmt.Println("WhereSaveAfter-->", food)

}

func WhereUpdates() {
	updateFood := Food{
		Name:  "lijiacai",
		Price: 1000000,
	}
	var food Food
	sql := db.Model(Food{}).Where("id == ?", 5)
	sql.Take(&food)
	fmt.Println("WhereUpdatesBefore-->", food)
	sql.Updates(&updateFood) // 多字段更新
	sql.Take(&food)
	fmt.Println("WhereUpdatesAfter-->", food)
}

删除数据
package test_gorm

import "fmt"

func Delete() {
	food := Food{}
	db.Model(Food{}).Take(&food)
	db.Model(Food{}).Where(&food).Delete(&food) // 按条件删除
	fmt.Println("Delete-->", food)
}

多表联查案例
package test_gorm

import "fmt"

type Topic struct {
	gorm.Model
	Title   string
	Content string
	UserId  int
	User    User `gorm:"foreignkey:UserId"` // 此时本表中的UserId关联User.Id
}

type User struct {
	gorm.Model
	Name string
}

func (obj User) TableName() string {
	return "user"
}

func (obj Topic) TableName() string {
	return "topic"
}


func CreateUser() {
	user := User{}
	user.Name = "lijiacai"
	db.Save(&user) // 创建数据可以用save或者create
}

func CreateTopic() {
	topic := Topic{}
	topic.Title = "Alice dream"
	topic.Content = "Yestoday,I will do ......."
	topic.UserId = 1
	db.Save(&topic)
}

func RalationSearch() {
	topic := Topic{}
	db.Model(Topic{}).Last(&topic)
	fmt.Println("RalationSearch-->topic--", topic)
	user := User{}
	db.Model(&topic).Association("User").Find(&user) // 关联外键查询
	fmt.Println("RalationSearch-->user--", user)
	topic.User = user
	fmt.Println("RalationSearch-->topic(user)--", topic)

}

type JoinRes struct {
	Topic
	User
}

func JoinSearch() {
	var joinRes []JoinRes
	err := db.Table("topic").Select("topic.*, user.*").Joins("left join user on topic.user_id=user.id").Find(&joinRes).Error // 多表联合查询,基本上都是sql写法
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println("JoinSearch-->", joinRes[0].Title, joinRes[0].Name, joinRes[0].Content)
}

数据库事务
package test_gorm

import (
	"errors"
	"github.com/jinzhu/gorm"
)

func Transaction(tx *gorm.DB) error {
	food := Food{}
	food.Name = "zmj"
	food.Price = 5
	food.TypeId = 3
	err := tx.Create(&food).Error
	return err
}

func TransactionPanic(tx *gorm.DB) error {
	food := Food{}
	food.Name = "zmj"
	food.Price = 88
	food.TypeId = 88
	err := tx.Create(&food).Error
	err = errors.New("主动异常")
	return err
}

执行
package main

import (
	"casbin-go/test-gorm"
	"fmt"
)

func TestFood() {
	test_gorm.CreateFood()
	test_gorm.FirstFood()
	test_gorm.LastFood()
	test_gorm.TakeFood()
	test_gorm.FindFood(2)
	test_gorm.Where()
	test_gorm.ModelTake()
	test_gorm.Select()
	test_gorm.WhereSave()
	test_gorm.WhereUpdates()
	test_gorm.Delete()
	test_gorm.Count()
	test_gorm.GetDB().Transaction(test_gorm.Transaction)
	test_gorm.LastFood()
	err := test_gorm.GetDB().Transaction(test_gorm.TransactionPanic).Error()
	fmt.Println(err)
	test_gorm.LastFood()
}

func TestTopicUser() {
	//test_gorm.CreateUser()
	//test_gorm.CreateTopic()
	test_gorm.RalationSearch()
	test_gorm.JoinSearch()

}

func main() {
	test_gorm.GetDB().AutoMigrate(&test_gorm.Food{}, &test_gorm.User{}, &test_gorm.Topic{}) // 自动创建表
	//TestFood()
	TestTopicUser()

}

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/990038.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-21
下一篇 2022-05-21

发表评论

登录后才能评论

评论列表(0条)

保存