安装gorm
$ go get -u gorm.io/gorm
$ go get -u gorm.io/driver/mysql
创建db实例
func InitDB() *gorm.DB {
host := "localhost"
port := "3306"
database := "mydb01"
username := "root"
password := "386mysql."
dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", username, password, host, port, database)
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
SkipDefaultTransaction: false,
NamingStrategy: schema.NamingStrategy{
SingularTable: true,
},
Logger: logger.Default.LogMode(logger.Info),
DisableAutomaticPing: false,
})
if err != nil {
panic("Connecting database failed: " + err.Error())
}
return db
}
定义用户模型
type User struct {
Id uint `gorm:"column:id; primaryKey; AUTO_INCREMENT; not null;" json:"user_id"`
Name string `gorm:"column:name;type:varchar(20);not null;" json:"user_name"`
Password string `gorm:"column:password;type:varchar(255);not null;" json:"-"`
Telphone string `gorm:"column:telphone;type:varchar(11);not null;unique;" json:"telphone"`
CreatedAt time.Time `gorm:"column:created_at;autoCreateTime;" json:"created_at"`
UpdatedAt time.Time `gorm:"column:updated_at;autoUpdateTime;" json:"updated_at"`
}
自动迁移模型
function main(){
r := gin.Default()
db := InitDB()
db.AutoMigrate(&User{})
panic(r.Run())
}
运行程序
$ go run main.go
查看生成数据表
mysql> use mydb01
Database changed
mysql> desc user;
+------------+-----------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+-----------------+------+-----+---------+----------------+
| id | bigint unsigned | NO | PRI | NULL | auto_increment |
| name | varchar(20) | NO | | NULL | |
| password | varchar(255) | NO | | NULL | |
| telphone | varchar(11) | NO | UNI | NULL | |
| created_at | datetime(3) | YES | | NULL | |
| updated_at | datetime(3) | YES | | NULL | |
+------------+-----------------+------+-----+---------+----------------+
6 rows in set (0.01 sec)
增加
type UserForm struct {
Name string `form:"name" binding:"required"`
Password string `form:"password" binding:"required"`
Telphone string `form:"telphone" binding:"required"`
}
r.POST("/user/add", func(c *gin.Context) {
var user UserForm
c.BindJSON(&user)
result := db.Create(&User{Name: user.Name, Password: user.Password, Telphone: user.Telphone})
if result.RowsAffected > 0 {
c.JSON(200, gin.H{
"data": "add success",
})
} else {
c.JSON(200, gin.H{
"msg": "add user failed",
})
}
})

删除
r.GET("/user/delete/:id", func(c *gin.Context) {
id := c.Param("id")
result := db.Delete(&User{}, id)
if result.RowsAffected > 0 {
c.JSON(200, gin.H{
"data": "delete success",
})
} else {
c.JSON(200, gin.H{
"msg": "delete user failed",
})
}
})

修改
r.PUT("/user/update/:id", func(c *gin.Context) {
id := c.Param("id")
var dbUser User
result := db.First(&dbUser, id)
if result.RowsAffected <= 0 {
c.JSON(500, gin.H{
"msg": "get user failed",
})
return
}
var form UserForm
c.BindJSON(&form)
result = db.Model(&dbUser).Updates(User{
Name: form.Name,
Password: form.Password,
Telphone: form.Telphone,
})
if result.RowsAffected > 0 {
c.JSON(200, gin.H{
"data": "update success",
})
} else {
c.JSON(200, gin.H{
"msg": "update user failed",
})
}
})

查找列表
r.GET("/user/list", func(c *gin.Context) {
var users []User
result := db.Find(&users)
if result.RowsAffected > 0 {
c.JSON(200, gin.H{
"data": users,
})
} else {
c.JSON(200, gin.H{
"msg": "get user list failed",
})
}
})

查找单个
r.GET("/user/detail/:id", func(c *gin.Context) {
id := c.Param("id")
var user User
result := db.First(&user, id)
if result.RowsAffected > 0 {
c.JSON(200, gin.H{
"data": user,
})
} else {
c.JSON(200, gin.H{
"msg": "get user detail failed",
})
}
})
