1、主
package main
import (
"fmt"
"wbGo/configs"
)
type Dades struct {
Id int
Name string
Age int
}
func main() {
//连接数据库
configs.BaseName("wbrj_sample")
var data []Dades
//查询
configs.Db.Raw("select * from dade where id>=?", 1).Find(&data)
fmt.Printf("%+v", data)
//插入
configs.Db.Table("dade").Create(map[string]interface{}{"name": "dade88"})
//更新
configs.Db.Table("dade").Where("id=?", 1).Updates(map[string]interface{}{"name": "dade99"})
//configs.Db.Table("dade").Where("id=?", 9).Updates(&Dades{Name: "7777"})
//dataMap := map[string]interface{}{"name": "111"}
//configs.Db.Table("dade").Where("id=?", 9).Updates(dataMap)
//给空
//configs.Db.Table("dade").Where("id=?", 9).Updates(map[string]interface{}{"name": "666", "age": nil})
//删除
//configs.Db.Table("dade").Where("id=?", 1).Delete(&Dades{})
configs.Db.Table("dade").Where("id=?", 2).Delete(map[string]interface{}{})
}
2、封装
package configs
import (
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
var Db *gorm.DB
// Mysql 方法返回一个 MysqlHandler 结构体
func BaseName(base string) {
dsn := "root:root@tcp(127.0.0.1:3306)/" + base + "?charset=utf8mb4&parseTime=True&loc=Local"
Dbs, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
//panic(err)
fmt.Println("连接失败", err)
}
Db = Dbs
fmt.Println("连接成功")
}
取值
package main
import (
"fmt"
"wbGo/configs"
)
type Dades struct {
Id int
Name string
Age int
}
func main() {
//连接数据库
configs.BaseName("wbrj_sample")
var data []Dades
//查询
configs.Db.Raw("select * from dade where id>=?", 1).Find(&data)
fmt.Printf("%+v", data[0].Id)
for _, v := range data {
fmt.Println(v.Id)
}
}