个人喜欢的GORM的使用方式(mysql)

本文介绍了个人偏爱的GORM在MySQL数据库中的应用,包括准备工作,如导入必要的包,建立MySQL连接,以及详细阐述了数据库操作,涵盖增、删、改、查等基本操作,并提到了左连接的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

个人喜欢的GORM的使用方式(mysql)

准备工作

  • 导包
go get -u github.com/jinzhu/gorm
import(
	"github.com/jinzhu/gorm"
    _ "github.com/jinzhu/gorm/dialects/mysql"
)

连接MySQL

//用户名:密码@(连接地址)/数据库名?连接设置
db, err := gorm.Open("mysql", 	"root:123456@(192.168.56.129:3307)/docker3?charset=utf8mb4")
	if err != nil {
		fmt.Println(err)
		return
	}

数据库操作

type Tom struct {
	Id      int 
	Name    string
	Score   int
	Created int64
}

func Insert(){
    tt := &Tom{
		Name:    "huang",
		Score:   78,
		Created: time.Now().Unix(),
	}
	db.Table("tom").Create(tt)
    //insert into tom (name,score,created)vlaue('huang',78,1640921525)
}
func Delete(){
    db.Table("tom").Delete("","id=?",3)
    //delete from tom where id = 3
}
func Update(){
        tt := &Tom{
		Name:    "huang",
		Score:   78,
		Created: time.Now().Unix(),
	}
    db.Table("tom").Where("id=?", 29).Update(&tt)
    //update tom set name='huang',score=78,created=1640921525 where id=29
    
    db.Table("tom").Where("id=?",29).Update("name","sam")
    //update tom set name=sam where id=29
}
func Select(){
    var (
    	name string
        score int
    )
    ns := make([]string,0) db.Table("tom").Select("name,score").Where("id=?",29).Row().Scan(&name,&score)
    fmt.Printf("name:%s,score:%d\n",name,score)
    //select name,score from tom where id =29
    rows,err := db.Table("tom").Select("name").Where("id >?",29).Rows()
    //select namefrom tom where id >29
    if err != nil{
        fmt.Println(err)
        return
    }
    for rows.Next(){
       var n string
        err = rows.Scan(&n)
        if err !=nil{
			continue
        }
        ns = append(ns,n)
    }
    fmt.Println(ns)
}
  • 左连接
func LeftJoin(){
    var class int
	db.Table("class").Select("class").Joins("left join tom on tom.id=class.uid").Where("tom.name=?","sam").Row().Scan(&class)
    //select class from class join tom on tom.id=class.uid where tom.name='sam'
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值