新增数据
db, _ := gorm.Open("mysql", "root:root@/test?charset=utf8mb4&parseTime=True&loc=Local")
defer db.Close()
// 打开日志日志,查看执行的sql
db.LogMode(true)
// 新增数据
news := model.NewsModel{Title:"新闻标题4",Content:"新闻内容4"}
affectedRow := db.Table("news").Create(&news).RowsAffected
fmt.Println("受影响函数:",affectedRow) //打印:受影响函数: 1
// 新增数据的ID
fmt.Println(news.Id) //打印:4
往news表插入一条。
在gin框架中实现简单的api查询
package dao
import (
"github.com/gin-gonic/gin"
"github.com/jinzhu/gorm"
"live.go.com/model"
)
//获取新闻详细
func GetNewsDetail(ctx *gin.Context) {
db, _ := gorm.Open("mysql", "root:root@/test?charset=utf8mb4&parseTime=True&loc=Local")
defer db.Close()
// 打开日志日志,查看执行的sql
db.LogMode(true)
// 获取路由参数
newsId := ctx.Param("news_id")
// 开始查询数据
news := model.NewsModel{}
db.Table("news").Find(&news, newsId)
// 返回json
ctx.JSON(200, news)
}
路由如何调用?
package main
import (
"github.com/gin-gonic/gin"
_ "github.com/go-sql-driver/mysql"
"live.go.com/dao"
)
func main() {
// 默认路由对象
router := gin.Default()
// 新闻路由分组
newsRouter := router.Group("/news")
{
// 获取某条新闻
newsRouter.GET("/:news_id",dao.GetNewsDetail)
}
// 默认启动的是8080端口
router.Run()
}

封装 db初步
新建db/MyDB.go
package db
import (
_ "github.com/go-sql-driver/mysql"
"github.com/jinzhu/gorm"
"log"
)
var DBHelper *gorm.DB
var err error
//初始化函数,引入包会自动执行
func init() {
// 连接数据库
DBHelper, err = gorm.Open("mysql", "root:root@/test?charset=utf8mb4&parseTime=True&loc=Local")
if err != nil {
log.Fatal(err)
}
// 开启log日志
DBHelper.LogMode(true)
}
然后dao层的GetNewsDetail()方法就可以使用我们封装的db
func GetNewsDetail(ctx *gin.Context) {
// 获取路由参数
newsId := ctx.Param("news_id")
// 开始查询数据
news := model.NewsModel{}
db.DBHelper.Table("news").Find(&news, newsId)
// 返回json
ctx.JSON(200, news)
//db.DBHelper.Close() //思考:这里
}
本文介绍了如何使用GORM在Go中进行数据新增,并展示了在Gin框架内创建简单的API查询。同时,探讨了数据库操作的初步封装,包括路由配置和DAO层的方法设计。
1027

被折叠的 条评论
为什么被折叠?



