首页 > 数据库 >Go Gin+MySQL实现增删改查

Go Gin+MySQL实现增删改查

时间:2024-01-10 14:55:42浏览次数:38  
标签:err 改查 JSON user context MySQL Go gin id

一、概述

  使用Gin框架+MySQL数据库实现增删改查(原生sql)

  实现步骤:

    1.导入Gin框架

go get -u github.com/gin-gonic/gin

    2.引入MySQL驱动

go get -u github.com/go-sql-driver/mysql

    3.注册Gin路由

// 注册用户路由
func RegisterUser() {
    //实例化一个路由
    router := gin.Default()
    //注册增删改查路由
    router.POST("/addUser", addUserHandler)
    router.GET("/getUsers", getUsersHandler)
    router.GET("/getUserById", getUserById)
    router.POST("/updateUser/:id", updateUserHandler)
    router.POST("/deleteUser", deleteUserHandler)
    router.Run(":8888")
}

    4.实现路由方法

      以上路径后面就是路由需要实现的方法,如:addUserHandler

    5.连接数据库

// 获取数据库连接对象
func getDB(info string) *sql.DB {
    sqlConnectStr := "root:123456@tcp(localhost:3306)/tony_cursor?charset=utf8&parseTime=true&loc=Local"
    SQLDB, err := sql.Open("mysql", sqlConnectStr)
    if err != nil {
        fmt.Println("数据库打开失败", err)
        // return
    }
    //测试与数据库建立的连接
    err = SQLDB.Ping()
    if err != nil {
        fmt.Println("数据库连接失败", err)
        // return
    } else {
        fmt.Println("数据库连接成功")
    }
    // defer SQLDB.Close()
    fmt.Println(info)
    return SQLDB
}

 

二、代码示例

  1.添加用户

  SQLDB := getDB("添加用户")
    //解析请求实体中的数据
    var user User
    err1 := context.ShouldBindJSON(&user)
    fmt.Println("接收到用户请求的数据:", user)
    fmt.Println("创建时间:", user.CreateTime)
    if err1 != nil { //如果出错则返回错误信息
        context.JSON(400, gin.H{ //说明是客户端传参有问题
            "error": "Invalid request body"})
        return
    }
    fmt.Println("开始执行sql")
    //执行插入操作并执行返回结果(执行原生sql语句)
    sql := "insert into user (name,pwd,head_img,phone,create_time) values (?,?,?,?,?)"
    fmt.Println(user.Name, user.Pwd, user.Phone, user.HeadImg, user.Phone, user.CreateTime)
    _, mErr := SQLDB.Exec(sql, user.Name, user.Pwd, user.HeadImg, user.Phone, user.CreateTime)
    if mErr != nil { //说明是服务端出现异常
        context.JSON(500, gin.H{
            "error": "Failed to create user" + mErr.Error()})
        fmt.Println(mErr)
        return
    }
    fmt.Println("sql执行完成开始给客户端返回正确结果")
    //如果都没有问题则返回200
    context.JSON(200, gin.H{
        "message": "User created successfully"})

  

 

  2.获取用户列表

SQLDB := getDB("查询用户列表")
    rows, err := SQLDB.Query("select id,name,head_img,phone,create_time from user")
    if err != nil {
        context.JSON(500, gin.H{
            "error": err.Error()})
        return
    }
    defer rows.Close()

    //解析查询结果并返回json形式的用户列表
    users := []User{}
    for rows.Next() {
        var user User
        err1 := rows.Scan(&user.Id, &user.Name, &user.HeadImg, &user.Phone, &user.CreateTime)
        if err1 != nil {
            context.JSON(500, gin.H{
                "error": err1.Error()})
            return
        }
        users = append(users, user)
    }
    context.JSON(200, gin.H{
        "data": users})

   3.通过用户id获取特定用户

   SQLDB := getDB("根据用户id查询用户")
    id := context.Query("id") //这里指的是接受param中的参数
    fmt.Println("用户id:", id)
    row := SQLDB.QueryRow("select id,name,head_img,phone,create_time from user where id=?", id)
    if row.Err() != nil {
        context.JSON(500, gin.H{"error": row.Err().Error()})
        return
    }
    var user User
    err := row.Scan(&user.Id, &user.Name, &user.HeadImg, &user.Phone, &user.CreateTime)
    if err != nil {
        context.JSON(500, gin.H{"error": err.Error()})
        return
    }
    context.JSON(200, gin.H{"data": user})

   4.根据用户id修改指定用户

SQLDB := getDB("更新用户信息")
    var id string = context.Param("id") //从请求的url中获取参数(restfull)
    var user User
    err2 := context.ShouldBindJSON(&user) //接收请求参数(json格式的)
    if err2 != nil {
        context.JSON(400, gin.H{
            "error": err2.Error()})
        return
    }
    ret, err1 := SQLDB.Exec("update user set name=? where id=?", user.Name, id)
    if err1 != nil {
        context.JSON(500, gin.H{
            "error": err1.Error()})
        return
    }
    mId, err3 := ret.LastInsertId()
    if err3 != nil {
        context.JSON(500, gin.H{"error": err3.Error()})
        return
    }
    context.JSON(200, gin.H{"data": mId})

   5.根据用户id逻辑删除指定指定用户

SQLDB := getDB("删除用户信息")
    var user User
    err := context.ShouldBindJSON(&user)
    if err != nil {
        context.JSON(400, gin.H{"error": err.Error()})
        return
    }
    _, err1 := SQLDB.Exec("update user set deleted=1 where id=?", user.Id)
    if err1 != nil {
        context.JSON(500, gin.H{"error": err1.Error()})
        return
    }
    context.JSON(200, gin.H{"data": "delete user successfuly"})

  6.对用户表进行增删改查完整代码

package controller

import (
    "database/sql"
    "fmt"

    "github.com/gin-gonic/gin"
    _ "github.com/go-sql-driver/mysql"
)

// 用户实体
type User struct {
    Id         int64  `json:"id"`
    Name       string `json:"name"`
    Pwd        string `json:"pwd"`
    HeadImg    string `json:"head_img"`
    Phone      string `json:"phone"`
    CreateTime string `json:"create_time"`
    UpdateTime string `json:"update_time"`
    Sort       int    `json:"sort"`
    CreateUser int64  `json:"create_user"`
    UpdateUser int64  `json:"update_user"`
    Deleted    int    `json:"deleted"`
}

// 注册用户路由
func RegisterUser() {
    //实例化一个路由
    router := gin.Default()
    //注册增删改查路由
    router.POST("/addUser", addUserHandler)
    router.GET("/getUsers", getUsersHandler)
    router.GET("/getUserById", getUserById)
    router.POST("/updateUser/:id", updateUserHandler)
    router.POST("/deleteUser", deleteUserHandler)
    router.Run(":8888")
}

// 添加新用户
func addUserHandler(context *gin.Context) {
    SQLDB := getDB("添加用户")
    //解析请求实体中的数据
    var user User
    err1 := context.ShouldBindJSON(&user)
    fmt.Println("接收到用户请求的数据:", user)
    fmt.Println("创建时间:", user.CreateTime)
    if err1 != nil { //如果出错则返回错误信息
        context.JSON(400, gin.H{ //说明是客户端传参有问题
            "error": "Invalid request body"})
        return
    }
    fmt.Println("开始执行sql")
    //执行插入操作并执行返回结果(执行原生sql语句)
    sql := "insert into user (name,pwd,head_img,phone,create_time) values (?,?,?,?,?)"
    fmt.Println(user.Name, user.Pwd, user.Phone, user.HeadImg, user.Phone, user.CreateTime)
    _, mErr := SQLDB.Exec(sql, user.Name, user.Pwd, user.HeadImg, user.Phone, user.CreateTime)
    if mErr != nil { //说明是服务端出现异常
        context.JSON(500, gin.H{
            "error": "Failed to create user" + mErr.Error()})
        fmt.Println(mErr)
        return
    }
    fmt.Println("sql执行完成开始给客户端返回正确结果")
    //如果都没有问题则返回200
    context.JSON(200, gin.H{
        "message": "User created successfully"})
}

// 获取用户列表
func getUsersHandler(context *gin.Context) {
    SQLDB := getDB("查询用户列表")
    rows, err := SQLDB.Query("select id,name,head_img,phone,create_time from user")
    if err != nil {
        context.JSON(500, gin.H{
            "error": err.Error()})
        return
    }
    defer rows.Close()

    //解析查询结果并返回json形式的用户列表
    users := []User{}
    for rows.Next() {
        var user User
        err1 := rows.Scan(&user.Id, &user.Name, &user.HeadImg, &user.Phone, &user.CreateTime)
        if err1 != nil {
            context.JSON(500, gin.H{
                "error": err1.Error()})
            return
        }
        users = append(users, user)
    }
    context.JSON(200, gin.H{
        "data": users})
}

func getUserById(context *gin.Context) {
    SQLDB := getDB("查询用户列表")
    id := context.Query("id") //这里指的是接受param中的参数
    fmt.Println("用户id:", id)
    row := SQLDB.QueryRow("select id,name,head_img,phone,create_time from user where id=?", id)
    if row.Err() != nil {
        context.JSON(500, gin.H{"error": row.Err().Error()})
        return
    }
    var user User
    err := row.Scan(&user.Id, &user.Name, &user.HeadImg, &user.Phone, &user.CreateTime)
    if err != nil {
        context.JSON(500, gin.H{"error": err.Error()})
        return
    }
    context.JSON(200, gin.H{"data": user})

}

// 更新用户信息
func updateUserHandler(context *gin.Context) {
    SQLDB := getDB("更新用户信息")
    var id string = context.Param("id") //从请求的url中获取参数(restfull)
    var user User
    err2 := context.ShouldBindJSON(&user) //接收请求参数(json格式的)
    if err2 != nil {
        context.JSON(400, gin.H{
            "error": err2.Error()})
        return
    }
    ret, err1 := SQLDB.Exec("update user set name=? where id=?", user.Name, id)
    if err1 != nil {
        context.JSON(500, gin.H{
            "error": err1.Error()})
        return
    }
    mId, err3 := ret.LastInsertId()
    if err3 != nil {
        context.JSON(500, gin.H{"error": err3.Error()})
        return
    }
    context.JSON(200, gin.H{"data": mId})

}

// 删除用户
func deleteUserHandler(context *gin.Context) {
    SQLDB := getDB("删除用户信息")
    var user User
    err := context.ShouldBindJSON(&user)
    if err != nil {
        context.JSON(400, gin.H{"error": err.Error()})
        return
    }
    _, err1 := SQLDB.Exec("update user set deleted=1 where id=?", user.Id)
    if err1 != nil {
        context.JSON(500, gin.H{"error": err1.Error()})
        return
    }
    context.JSON(200, gin.H{"data": "delete user successfuly"})

}

// 获取数据库连接对象
func getDB(info string) *sql.DB {
    sqlConnectStr := "root:123456@tcp(localhost:3306)/tony_cursor?charset=utf8&parseTime=true&loc=Local"
    SQLDB, err := sql.Open("mysql", sqlConnectStr)
    if err != nil {
        fmt.Println("数据库打开失败", err)
        // return
    }
    //测试与数据库建立的连接
    err = SQLDB.Ping()
    if err != nil {
        fmt.Println("数据库连接失败", err)
        // return
    } else {
        fmt.Println("数据库连接成功")
    }
    // defer SQLDB.Close()
    fmt.Println(info)
    return SQLDB
}

  7.使用

// GinTest.go
package main

import (
    "fmt"

    "go_workspace/controller"
)

func main() {
    controller.RegisterUser()
    fmt.Println("Hello World!")
}

  8.完结

  

标签:err,改查,JSON,user,context,MySQL,Go,gin,id
From: https://www.cnblogs.com/tony-yang-flutter/p/17956477

相关文章

  • MySql 中 INSTR() 用法
    在MySQL中,INSTR()函数用于查找一个字符串中是否包含另一个指定的子串,并返回该子串在原始字符串中第一次出现的位置。以下是INSTR()函数的语法:INSTR(str,substr)其中,str是要搜索的目标字符串;substr是要查找的子字符串。如果str包含substr,则返回substr在str中第一......
  • 解决mac arm 中 goland 无法 debug 问题
    新电脑不知道装了什么,导致无法debug现象可以run,没有问题不能debug,报错信息如下单元测试报错^Cgotooltest2json:signal:interruptmain方法debug报错^Ccouldnotlaunchprocess:stubexitedwhilewaitingforconnection:signal:interrupt解决之路网上找遍......
  • MySql 中 SUBSTRING_INDEX()用法
    SUBSTRING_INDEX()函数用于从一个指定分隔符分隔的字符串中提取子串。它返回一个字符串,包含在原始字符串中出现在指定分隔符之前或之后的所有字符。以下是SUBSTRING_INDEX()函数的语法:SUBSTRING_INDEX(str,delim,count)其中,str是要分割的字符串;delim是指定的分隔符;count......
  • centos安装mysql8,银河麒麟安装mysql8,arm(aarch)架构,rpm包,完全离线安装
    作者主页:https://www.cnblogs.com/milkbox/参考:软件包下载:https://rpmfind.net/linux/rpm2html/search.phpMySQL::DownloadMySQLCommunityServer主要教程:十二、MySQL8.0.32离线安装(适用于Linux-CentOS7)_linux离线安装libaio-CSDN博客本教程以银河麒麟v10为例注......
  • ubuntu安装mysql8,debian安装mysql8,linux安装mysql8,x86_64架构,deb包
    作者主页:https://www.cnblogs.com/milkbox参考:修改大小写:MySQL8.0安装后更改不区分大小写!包你必生效!_mysql8.0不区分大小写-CSDN博客整个安装过程建议在root权限下进行。需要网络来下载相关依赖,如果你的系统已经存在相关以来,那么就可以离线安装。下载与解压去官网下载mys......
  • 6 修改表 -- MySQL数据库
    在大多数情况下,表结构更改时都使用altertable语句。1.修改表类型#语法mysql>altertable表名modify[column]列定义[first|after列名];实例:修改表emp的ename字段,将varchar(10)改为将varchar(20)mysql>altertableempmodifyenamevarchar(20);2.......
  • 【golang】GO之认证与授权
    一般公司项目比较多,比较分散,但是对于都是公司的用户来说,用户数据一般是共享的,所以集成统一认证与授权的功能一般就必不可少,这样可以实现一个用户,分配一点权限,能访问公司很多项目.一般的认证与授权方案有OAuth、分布式Session、OpenID和JWT等.目前常用的是OAuth2,其......
  • mysql_native_password 身份验证插件在未来版本中移除
    自MySQL8.0.34起,mysql_native_password身份验证插件已被弃用,并可能在MySQL的未来版本中移除。移除意味着:Javajdbc配置文件以及后端大数据的账号密码,必须更改为caching_sha2_password认证模式,否则无法连接MySQL数据库。如果业务系统今后升级MySQL8.0,这块需要加以适配。如果......
  • 实战-Docker 安装 MySQL
    使用Docker命令安装镜像官方文档:https://hub.docker.com/_/mysqlrm-rf/opt/mysqlmkdir-p/opt/mysql/data/opt/mysql/init/opt/mysql/confdockerrun-d\--namemysql\-p3306:3306\-eTZ=Asia/Shanghai\-eMYSQL_ROOT_PASSWORD=123456\-v/o......
  • python diango后端支持运行脚本+vue前端支持脚本运行
    #使用Python内置的subprocess模块来执行Python脚本#使用注意:#1,依赖包需要提前导入至脚本中#2,script_path变量是脚本得绝对路径#3,filename变量是脚本得名称#搭配vue页面使用#想法:页面支持导入,编辑,执行脚本#导入:默认指定路径下,需要填......