实现go语言下gin框架与gorm的数据库增删改查的操作
Win10 + goland
1、goLand下创建新功能 ginGormTestProject
试运行一下helloworld
package main
import "fmt"
func main() {
fmt.Println("Hello World")
}
2、开始使用gin框架,让他成为一个web应用
package main
import “github.com/gin-gonic/gin”
func main() {
r := gin.Default()
r.GET(“/”, func(c *gin.Context) {
c.String(200, “Hello World”)
})
r.Run()
}
3、运行后报错如下:main.go:3:8: no required module provides package github.com/gin-gonic/gin: working directory is not part of a module
终端下去安装一下gin框架并执行go mod命令:
go get -u github.com/gin-gonic/gin
go mod init gin
go mod edit -require github.com/gin-gonic/gin@latest
4、编译运行后,如下则启动完成
5、浏览器访问http://localhost:8080/
6、我们继续构建一个API,但不是一个Web应用程序,用JSON方式响应
修改代码:
7、执行:
8、下面开始应用gorm http://jinzhu.me/gorm/,Gorm是用于go的对象关系映射(ORM)框架。
安装gorm框架:
go get -u github.com/jinzhu/gorm
9、安装gorm mysql驱动
go get github.com/go-sql-driver/mysql
安装前需要先检查git是否安装,我这里没有安装git,所以先去下载安装https://gitforwindows.org/下载
https://git-scm.com/downloads 这个网址下载会更快一点~~~
10、安装后运行报错:
panic: 连接数据库失败:dial tcp 127.0.0.1:3306: connectex: No connection could be made because the target machine actively refused it.
还没有安装Mysql,下载地址:https://dev.mysql.com/downloads/repo/yum/
安装参考资料链接:https://www.cnblogs.com/honeynan/p/12408119.html
按照教程操作,一系列复杂操作,终于把mysql给搞定了。
11、安装数据库操作工具 Navicate
通过Navicate 创建一个开发测试用的数据库test
12、运行一个数据库增删改查的测试代码
package main
// only need mysql OR sqlite
// both are included here for reference
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
)
var db *gorm.DB
var err error
type Person struct {
ID uint `json:"id" gorm:"primary_key"`
FirstName string `json:"firstname"`
LastName string `json:"lastname"`
City string `json:"city"`
}
func main() {
// NOTE: See we’re using = to assign the global var
// instead of := which would assign it only in this function
//db, err = gorm.Open("sqlite3", "./gorm.db")
//db, err := gorm.Open("mysql", "root:root@tcp(127.0.0.1:3306)/test?charset=utf8&parseTime=True&loc=Local")
//
//if err != nil {
// fmt.Println(err)
// panic(err)
//}
//defer db.Close()
db :=Dbinit()
db.AutoMigrate(&Person{})
if !db.HasTable(&Person{}) {
if err := db.Set("gorm:table_options", "ENGINE=InnoDB DEFAULT CHARSET=utf8").CreateTable(&Person{}).Error; err != nil {
panic(err)
}
}
r := gin.Default()
//localhost:8080/people
r.GET("/people/", GetPeople)
//localhost:8080/people/1
r.GET("/people/:id", GetPerson)
//localhost:8080/people {"id":4,"firstname":"Elvis","lastname":"Presley","city":"beijing"}
r.POST("/people", CreatePerson)
//localhost:8080/people {"id":4,"firstname":"Elvis","lastname":"Presley","city":"beijing"}
r.PUT("/people/:id", UpdatePerson)
//localhost:8080/people/1
r.DELETE("/people/:id", DeletePerson)
r.Run(":8080")
}
func DeletePerson(c *gin.Context) {
id := c.Params.ByName("id")
var person Person
db = Dbinit()
d := db.Where("id = ?", id).Delete(&person)
fmt.Println(d)
c.JSON(200, gin.H{"id #" + id: "deleted"})
}
func UpdatePerson(c *gin.Context) {
var person Person
id := c.Params.ByName("id")
db = Dbinit()
if err := db.Where("id = ?", id).First(&person).Error; err != nil {
c.AbortWithStatus(404)
fmt.Println(err)
}
c.BindJSON(&person)
db.Save(&person)
c.JSON(200, person)
}
func CreatePerson(c *gin.Context) {
var person Person
c.BindJSON(&person)
db = Dbinit()
db.Create(&person)
c.JSON(200, person)
}
func GetPerson(c *gin.Context) {
id := c.Params.ByName("id")
var person Person
db = Dbinit()
if err := db.Where("id = ?", id).First(&person).Error; err != nil {
c.AbortWithStatus(404)
fmt.Println(err)
} else {
c.JSON(200, person)
}
}
func GetPeople(c *gin.Context) {
var people []Person
db = Dbinit()
if err := db.Find(&people).Error; err != nil {
c.AbortWithStatus(404)
fmt.Println(err)
} else {
c.JSON(200, people)
}
}
func Dbinit() *gorm.DB {
db := NewConn()
//SetMaxOpenConns用于设置最大打开的连接数
//SetMaxIdleConns用于设置闲置的连接数
db.DB().SetMaxIdleConns(10)
db.DB().SetMaxOpenConns(100)
// 启用Logger,显示详细日志
db.LogMode(true)
// 自动迁移模式
//db.AutoMigrate(&Model.UserModel{},
// &Model.UserDetailModel{},
// &Model.UserAuthsModel{},
//)
return db
}
func NewConn() *gorm.DB {
db, err := gorm.Open("mysql", "root:123456@tcp(127.0.0.1:3306)/test?charset=utf8&parseTime=True&loc=Local")
if err != nil {
panic("连接数据库失败:" + err.Error())
}
return db
}
13、注意需要修改一下自己的mysql的账号、密码,然后再运行程序。
14、可以使用Tester接口测试工具进行测试。
结束