一定要看文档哦
https://gorm.io/zh_CN/docs/
安装gorm
命令
go get -u gorm.io/gorm
go get -u gorm.io/driver/sqlite
go get -u gorm.io/driver/mysql
出现问题
安装gcc
下载地址https://www.mingw-w64.org/
添加环境变量
验证是否安装正确
gcc -v
连接MySQL数据库并且迁移创建一个数据表
参考链接https://gorm.io/zh_CN/docs/migration.html
package main
import (
"log"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
type Product struct {
gorm.Model
Code string
Price uint
}
func main() {
dsn := "root:root@tcp(127.0.0.1:3306)/go_orm?charset=utf8mb4"
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
log.Fatal(err)
}
db.AutoMigrate(&Product{})
}
运行结果数据库多了一个表
创建数据
package main
import (
"log"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
type Product struct {
gorm.Model
Code string
Price uint
}
func main() {
dsn := "root:root@tcp(127.0.0.1:3306)/go_orm?charset=utf8mb4"
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
log.Fatal(err)
}
p := Product{
Code: "1001",
Price: 100,
}
db.Create(&p)
}
多运行几次多存点数据后面用
查找数据
根据主键查找
package main
import (
"fmt"
"log"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
type Product struct {
gorm.Model
Code string
Price uint
}
func main() {
dsn := "root:root@tcp(127.0.0.1:3306)/go_orm?charset=utf8mb4"
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
log.Fatal(err)
}
var p Product
db.First(&p)
fmt.Printf("p: %v\n", p)
}
注意看注释前后运行结果不一样 出现上面的error是应为在连接数据库时候没有加下面参数
dsn := "root:root@tcp(127.0.0.1:3306)/go_orm?charset=utf8mb4&parseTime=true"
根据条件查询
package main
import (
"fmt"
"log"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
type Product struct {
gorm.Model
Code string
Price uint
}
func main() {
dsn := "root:root@tcp(127.0.0.1:3306)/go_orm?charset=utf8mb4&parseTime=true"
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
log.Fatal(err)
}
var p Product
db.First(&p, "code = ?", "1002")
fmt.Printf("p: %v\n", p)
}
更新数据
package main
import (
"log"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
type Product struct {
gorm.Model
Code string
Price uint
}
func main() {
dsn := "root:root@tcp(127.0.0.1:3306)/go_orm?charset=utf8mb4&parseTime=true"
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
log.Fatal(err)
}
var p Product
db.First(&p, 1)
db.Model(&p).Updates(map[string]interface{}{"Price": 200, "Code": "1006"})
}
删除数据
package main
import (
"log"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
type Product struct {
gorm.Model
Code string
Price uint
}
func main() {
dsn := "root:root@tcp(127.0.0.1:3306)/go_orm?charset=utf8mb4&parseTime=true"
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
log.Fatal(err)
}
var p Product
db.First(&p, 1)
db.Delete(&p)
}
|