当前位置:网站首页>gin中改进版curd接口例子
gin中改进版curd接口例子
2022-08-09 08:46:00 【tjg888888】
package main
import (
"database/sql"
"fmt"
"strconv"
"github.com/gin-gonic/gin"
"net/http"
_ "github.com/jinzhu/gorm/dialects/sqlite"
_"github.com/go-sql-driver/mysql"
"log"
)
var db *sql.DB
var err error
//数据表user,字段分别为id,name,gender,age
type User struct {
ID int `json:"id"`
Name string `json:"name"`
Gender int `json:"gender"`
Age int `json:"age"`
}
func main() {
//初始化数据库连接池,连接信息(数据库类型mysql,数据库用户名root,数据库密码为空,数据库ip:127.0.0.1,端口3306,数据库名imooc)
db,err=sql.Open("mysql", "root:@tcp(127.0.0.1:3306)/imooc?parseTime=true")
if err != nil{
log.Fatalln(err)
}
//定义数据库操作
defer db.Close()
//设置数据库空闲连接
db.SetMaxIdleConns(20)
//设置数据库最大打开连接
db.SetMaxOpenConns(20)
if err := db.Ping(); err != nil{
log.Fatalln(err)
}
//设置路由
router := gin.Default()
//增加一条记录
router.POST("/add", func(c *gin.Context) {
//接值
name:=c.Request.FormValue("name")
cgender:=c.Request.FormValue("gender")
gender,_:=strconv.Atoi(cgender)
cage:=c.Request.FormValue("age")
age,_:=strconv.Atoi(cage)
user:=User{
Name:name,
Gender: gender,
Age: age,
}
id:=user.Create()
msg:=fmt.Sprintf("insert successful %d",id)
//最后返回json格式数据
c.JSON(http.StatusOK,gin.H{
"msg":msg,
})
})
//查询列表
router.GET("/list", func(c *gin.Context) {
rs,_:=getRows()
c.JSON(http.StatusOK,gin.H{
"list":rs,
})
})
//查询单条记录
router.GET("/find", func(c *gin.Context) {
//接值
ids:=c.Request.FormValue("id")
id,_:=strconv.Atoi(ids)
rs,_:=getRow(id)
c.JSON(http.StatusOK,gin.H{
"result":rs,
})
})
//修改单条记录
router.PUT("/update", func(c *gin.Context) {
//接值
cid:=c.Request.FormValue("id")
id,_:=strconv.Atoi(cid)//将字符串类型转换成int操作,int转字符串: Itoa()
name:=c.Request.FormValue("name")
cgender:=c.Request.FormValue("gender")
gender,_:=strconv.Atoi(cgender)
cage:=c.Request.FormValue("age")
age,_:=strconv.Atoi(cage)
//创建user对象
user:=User{ID: id,Name:name,Gender:gender,Age:age}
row:=user.Update()
//返回的msg内容
msg:=fmt.Sprintf("update user successful %d",row)
//返回json数据
c.JSON(http.StatusOK,gin.H{
"msg":msg,
})
})
//删除某条记录
router.DELETE("delete", func(c *gin.Context) {
//接值
cid:=c.Request.FormValue("id")
//利用strconv函数的Atoi()方法将字符串类型cid转换为int整型
id,_:=strconv.Atoi(cid)
row := Delete(id)
//返回提示信息msg
msg:=fmt.Sprint("delete successful %d",row)
//返回json数据
c.JSON(http.StatusOK,gin.H{
"msg":msg,
})
})
//本地监听8080端口运行该程序
router.Run("0.0.0.0:8080")
}
//增加
func (user *User) Create() interface{} {
rs,err:=db.Exec("insert into user (name,gender,age)value (?,?,?)",user.Name,user.Gender,user.Age)
if err!=nil{
log.Fatalln(err)
}
id,err:=rs.LastInsertId()
if err!=nil{
log.Fatalln(err)
}
return id
}
//查询列表
func getRows() (users []User,err error) {
rows,err:=db.Query("select * from user")
for rows.Next() {
user:=User{}
err :=rows.Scan(&user.ID,&user.Name,&user.Gender,&user.Age)
if err!=nil{
log.Fatalln(err)
}
users=append(users,user)
}
rows.Close()
return
}
//查询单条
func getRow(id int) (user User,err error) {
user =User{}
err=db.QueryRow("select * from user where id=?",id).Scan(&user.ID,&user.Name,&user.Gender,&user.Age)
return
}
//修改
func (user *User)Update()int64 {
rs,err:=db.Exec("update user set name=?,gender=?,age=? where id=?",user.Name,user.Gender,user.Age,user.ID)
if err!=nil{
log.Fatalln(err)
}
rows,err:=rs.RowsAffected()
if err!=nil{
log.Fatalln(err)
}
return rows
}
//删除
func Delete(id int) interface{} {
rs,err:=db.Exec("delete from user where id=?",id)
if err!=nil{
log.Fatal()
}
rows,err:=rs.RowsAffected()
if err!=nil{
log.Fatal()
}
return rows
}边栏推荐
- MySQL数据库
- nyoj306 走迷宫(搜索+二分)
- Euclid and the game
- Matlab, and nonlinear equations solving linear equations
- Tencent cloud server is modified to root login to install pagoda panel
- 数制之间的转换
- STM32 如何知道FLASH的使用情况
- 第五届蓝帽杯初赛 misc 赛后复现
- 解决iframe跳转时父页面仍然存在的问题
- + 6000 words, help you understand the Internet architecture evolution.
猜你喜欢
随机推荐
define 可变参数定义
VMware virtual machine cannot be connected to the Internet after forced shutdown
三次握手,四次挥手
leetcode 33. 搜索旋转排序数组 (二分经典题)
Where does detection go forward?
XCTF College War "Epidemic" Network Security Sharing Competition Misc wp
ctf misc 图片题知识点
图像识别后将识别结果整理成列表,点击列表可跳转到搜索页面
数据解析之bs4学习
makefile的foreach、filter、filter-out函数
MySQL数据库
NodeMCU(ESP8266) 接入阿里云物联网平台 踩坑之旅
Cookie and Session Details
requests之数据解析Xpath介绍
sizeof 结构体问题
深度学习时代的视频理解综述
【GNN终身学习】2022 CVPR 终身图学习
A watch - article HongMeng development practical experience
[MySQL]mysql: Solve the problem of [Err] 1093 - You can't specify target table 'table name' for update in FROM clause
Process synchronization and mutual exclusion problem









