当前位置:网站首页>gin中模型中增删改查+搜索分页

gin中模型中增删改查+搜索分页

2022-08-09 08:46:00 tjg888888

模型里代码:

package models

import (
   db "awesomeProject/databases"
   "fmt"
   _ "gopkg.in/gin-gonic/gin.v1/json"
)

type User struct {
   ID int `json:"id"`
   Name string `json:"name"`
   Gender int `json:"gender"`
   Age int `json:"age"`
}
//增加
func (user *User) AddUser() bool {
   var rs, err = db.SqlDB.Exec("insert into user (name,gender,age)value (?,?,?)", user.Name, user.Gender, user.Age)
   if err!=nil{
      return false
   }
   id,err:=rs.LastInsertId()
   fmt.Println(id)
   if err!=nil{
      return false
   }else{
      return true
   }
}
//修改
func (user *User) EditUser() bool  {
   rs,err:=db.SqlDB.Exec("update user set name=?,gender=?,age=? where id=?",user.Name,user.Gender,user.Age,user.ID)
   if err!=nil{
      return  false
   }
   id,err:=rs.RowsAffected()
   if err!=nil{
      return  false
   }else {
      fmt.Println(id)
      return  true
   }
}
//删除
func DeleteUser(Id int) bool {
   rs,err:=db.SqlDB.Exec("Delete from user where id=?",Id)
   if err!=nil{
      return  false
   }
   id,err:=rs.RowsAffected()
   if err!=nil{
      return false
   }else {
      fmt.Println(id)
      return true
   }
}
//列表
func GetUserList(pageno,pagesize int,search string)(users []User)  {
   //fmt.Println("搜索关键词",search)
   users=make([]User,0)
   //sql搜索分页查询语句
   if search!=""{
      rows,err:=db.SqlDB.Query("select * from user where name like '%"+search+"%' limit ?,?",(pageno-1)*pagesize,pagesize)
      //fmt.Println(rows.Close())
      if err!=nil{
         return nil
      }
      defer rows.Close()
      //数据添加到数据集中
      for rows.Next(){
         var user User
         rows.Scan(&user.ID,&user.Name,&user.Gender,&user.Age)
         users=append(users,user)
      }
      //fmt.Println(users)
      if err = rows.Err(); err != nil {
         return nil
      }
   }else{
      rows,err:=db.SqlDB.Query("select * from user  limit ?,?",(pageno-1)*pagesize,pagesize)
      //fmt.Println(rows.Close())
      if err!=nil{
          return nil
      }
      defer rows.Close()
      //数据添加到数据集中
      for rows.Next(){
         var user User
         rows.Scan(&user.ID,&user.Name,&user.Gender,&user.Age)
         users=append(users,user)
         //fmt.Println(users)
      }
      if err = rows.Err(); err != nil {
         return nil
      }
   }
   return  users
}
//用户数
func GetUserNum(search string)int{
   num:=0;
   //查询分页语句
   if search!=""{
      rows,err:=db.SqlDB.Query("select * from user where name like '%"+search+"%'")
      if err!=nil{
         return  0
      }
      defer rows.Close()
      for rows.Next(){
         num++;
      }
   }else {
      rows,err:=db.SqlDB.Query("select * from user")
      if err!=nil{
         return  0
      }
      defer rows.Close()
      for rows.Next(){
         num++
      }
   }
   return num
}
//获取单条数据
func GetUserById(Id int)(users * User)  {
   var user User
   err:=db.SqlDB.QueryRow("select * from user where id=?",Id).Scan(&user.ID,&user.Name,&user.Gender,&user.Age)
   if err!=nil{
      fmt.Println(err)
   }
   return &user
}

//根目录下main.go文件里代码:

package main

import (
   "database/sql"
   "github.com/gin-gonic/gin"
   "log"
   "net/http"
   "strconv"
   "awesomeProject/models"
)
var db *sql.DB
var err error

type User struct {
   ID int `json:"id"`
   Name string `json:"name"`
   Gender int `json:"gender"`
   Age int `json:"age"`
}
func main() {
   var err error
   //初始化数据库连接池,连接信息(数据库类型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",AddUserApi)
   //查询列表
   router.GET("/list",ListUserApi)
   //查询单条记录
   router.GET("/find",FindUserApi)
   //修改单条记录
   router.PUT("/update",UpdateUserApi)
   //删除某条记录
   router.DELETE("delete",DeleteUserApi)
   //本地监听8080端口运行该程序
   router.Run("0.0.0.0:8080")
}
//增加接口
func AddUserApi(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:=models.User{
      Name:name,
      Gender: gender,
      Age:    age,
   }
   //调用模型中增加方法
   user.AddUser()
}
//查询列表接口
func ListUserApi(c *gin.Context) {
   //参数
   search:=c.Request.FormValue("search")
   num:=c.Request.FormValue("pageno")
   pageno,_:=strconv.Atoi(num)
   if err!=nil{
      log.Fatalln(err)
   }
   //得到数据集
   datalist:=models.GetUserList(pageno,1,search)
   //得到记录的总数
   count:=models.GetUserNum(search)
   c.JSON(http.StatusOK,gin.H{
      "datalist":datalist,
      "count":count,
      "pagesize":1,
      "pageno":pageno,
   })
}
//查询单条记录接口
func FindUserApi(c *gin.Context)  {
   //参数
   ids:=c.Request.FormValue("id");
   id,_:=strconv.Atoi(ids);
   res:=models.GetUserById(id);
   c.JSON(http.StatusOK,gin.H{
      "res":res,
      "code":200,
   })
}
//修改单条记录接口
func UpdateUserApi(c *gin.Context)  {
   //接值
   ids:=c.Request.FormValue("id");
   id,_:=strconv.Atoi(ids);
   name:=c.Request.FormValue("name")
   cgender:=c.Request.FormValue("gender")
   gender,_:=strconv.Atoi(cgender)
   cage:=c.Request.FormValue("age")
   age,_:=strconv.Atoi(cage)
   //赋值
   user:=models.User{
      ID:id,
      Name:name,
      Gender: gender,
      Age:    age,
   }
   //调用模型中修改方法
   user.EditUser()
   c.JSON(http.StatusOK,gin.H{
      "msg":"修改成功",
      "code":200,
   })
}
//删除某条记录接口
func DeleteUserApi(c *gin.Context)  {
   //接值
   ids:=c.Request.FormValue("id");
   id,_:=strconv.Atoi(ids);
   models.DeleteUser(id)
   c.JSON(http.StatusOK,gin.H{
      "msg":"删除成功",
      "code":200,
   })
}


原网站

版权声明
本文为[tjg888888]所创,转载请带上原文链接,感谢
https://blog.csdn.net/tianjingang1/article/details/105254232