[ 还在写 ] Golang ORM库 Gorm 速通、基本操作
安装 mysql 驱动库
本以为安装了gorm就好了,实际上还要安装对应mysql的驱动库
import (
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
否则,中间那行代码是报红的。于是执行如下代码
go get gorm.io/driver/mysql
居然报错了go get: module gorm.io/driver/mysql: reading https://mirrors.aliyun.com/goproxy/gorm.io/driver/mysql/@v/list: 404 Not Found
推断是阿里镜像没有这个库,于是打开 cmd 输入
go env -w GOPROXY=https://goproxy.cn,direct
切换另外的镜像,成功下载
轻松尝试
package main
import (
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
type TMedicines struct {
ProductID int `gorm:"primaryKey;column:ProductID;type:int(11);not null" json:"-"`
ProductName string `gorm:"column:ProductName;type:varchar(100);default:''" json:"product_name"`
QuantityPerunit string `gorm:"column:QuantityPerunit;type:varchar(60);default:''" json:"quantity_perunit"`
Unit string `gorm:"column:Unit;type:varchar(56);default:''" json:"unit"`
Unitprice float64 `gorm:"column:Unitprice;type:decimal(12,2)" json:"unitprice"`
SupplierID string `gorm:"column:SupplierID;type:varchar(14);default:''" json:"supplier_id"`
SubcategoryID string `gorm:"column:SubcategoryID;type:char(14)" json:"subcategory_id"`
Photopath string `gorm:"column:Photopath;type:varchar(255);default:''" json:"photopath"`
Notes string `gorm:"column:notes;type:varchar(2000);default:''" json:"notes"`
Ytype string `gorm:"column:ytype;type:varchar(14)" json:"ytype"`
IsPrescribed []uint8 `gorm:"column:isPrescribed;type:bit(1)" json:"is_prescribed"`
IsStockOut []uint8 `gorm:"column:isStockOut;type:bit(1)" json:"is_stock_out"`
// gorm.Model
}
func main() {
dsn := "root:sql2008@tcp(127.0.0.1:3306)/test?charset=utf8mb4&parseTime=True&loc=Local"
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
panic(err)
}
// ^ 检索数据
var res []TMedicines
db.Table("t_medicines").Where("unitprice > ?", 25000).Find(&res)
fmt.Println(len(res))
fmt.Println(res)
}