1、连接mysql go 文件
package dbs
import (
"database/sql"
"fmt"
"log"
"time"
_ "github.com/go-sql-driver/mysql"
)
var MysqlDb *sql.DB
var MysqlDbErr error
// 初始化链接
func InitDB() (err error) {
dbDSN := fmt.Sprintf("root:root_pwd,1q,1@tcp(*.*.*.*:port)/tty01?charset=utf8")
// 打开连接失败
MysqlDb, MysqlDbErr = sql.Open("mysql", dbDSN)
//defer MysqlDb.Close();
if MysqlDbErr != nil {
log.Println("dbDSN: " + dbDSN)
panic("数据源配置不正确: " + MysqlDbErr.Error())
}
// 最大连接数
MysqlDb.SetMaxOpenConns(100)
// 闲置连接数
MysqlDb.SetMaxIdleConns(20)
// 最大连接周期
MysqlDb.SetConnMaxLifetime(100 * time.Second)
if MysqlDbErr = MysqlDb.Ping(); nil != MysqlDbErr {
panic("数据库链接失败: " + MysqlDbErr.Error())
}
return
}
2、 web main入口文件 操作mysql
package main
import (
"fmt"
"net/http"
"web_restful_api_mysql/dbs"
"github.com/gin-gonic/gin"
_ "github.com/go-sql-driver/mysql"
)
type User struct {
Id int `json:"id"`
Name string `json:"name"`
City string `json:"city"`
Age int `json:"age"`
}
func main() {
err := dbs.InitDB()
if err != nil {
fmt.Println("err ", err)
}
// // 通过切片存储
// users := make([]User, 0)
// rows, _ := dbs.MysqlDb.Query("SELECT * FROM book")
// // 遍历
// var user User
// for rows.Next() {
// rows.Scan(&user.Id, &user.Name, &user.Age)
// users = append(users, user)
// }
// fmt.Println(users, "长度", len(users))
// for i := 0; i < len(users); i++ {
// fmt.Println("id , title , price")
// fmt.Println(users[i].Id, users[i].Name, users[i].Age)
// }
router := gin.Default()
//根据id 展示
// router.GET("/user/:id", FindUser)
// 查询all
router.GET("user/all", UserList)
// 新增
router.POST("/user/add", UserAdd)
//修改
router.POST("/user/update", UpdateUser)
// 删除
router.POST("/user/delete", DeleteUser)
router.Run(":8001")
}
func FindUser(c *gin.Context) {
var (
user User
result gin.H
)
id := c.Param("id")
row := dbs.MysqlDb.QueryRow("select * from t_user where id = ?;", id)
err := row.Scan(&user.Id, &user.Name, &user.City, &user.Age)
if err != nil {
result = gin.H{
"result": nil,
"count": 0,
}
} else {
result = gin.H{
"result": user,
"count": 1,
}
}
c.JSON(http.StatusOK, result)
}
func UserList(c *gin.Context) {
var (
user User
users []User
)
rows, err := dbs.MysqlDb.Query("select * from t_user")
if err != nil {
fmt.Println("err==>", err.Error())
}
for rows.Next() {
err = rows.Scan(&user.Id, &user.Name, &user.City, &user.Age)
if err != nil {
fmt.Println("err ==>", err.Error())
}
users = append(users, user)
}
defer rows.Close()
c.JSON(http.StatusOK, gin.H{
"result": users,
"count": len(users),
})
}
func UserAdd(c *gin.Context) {
//获取 post接入值
// var buffer bytes.Buffer
fmt.Println("来了")
name := c.PostForm("name")
city := c.PostForm("city")
age := c.PostForm("age")
fmt.Println("来了", name, city, age)
stmt, err := dbs.MysqlDb.Prepare("insert into t_user (name,city,age) values (?,?,?)")
addRet, _ := stmt.Exec(name, city, age)
ins_nums, _ := addRet.RowsAffected()
if ins_nums > 0 {
if err != nil {
fmt.Println("err ->", err.Error())
}
_, err = stmt.Exec(name, city, age)
if err != nil {
fmt.Println("err-<", err.Error())
}
c.JSON(http.StatusOK, gin.H{
"message": "success",
"code": fmt.Sprintf("新插入数据: %s", name),
})
} else {
c.JSON(http.StatusOK, gin.H{
"message": fmt.Sprintf("%s add error created", name),
"code": 333,
})
}
}
func UpdateUser(c *gin.Context) {
id := c.PostForm("id")
// id := c.Param("id")
name := c.PostForm("name")
city := c.PostForm("city")
age := c.PostForm("age")
stmt, err := dbs.MysqlDb.Prepare("update t_user set name=?,city=?,age=? where id=?")
if err != nil {
fmt.Println("err--", err.Error())
}
update, _ := stmt.Exec(name, city, age, id)
ins_nus, _ := update.RowsAffected()
if ins_nus > 0 {
fmt.Println("修改成功", id)
c.JSON(http.StatusOK,gin.H{
"message": fmt.Sprintf("id : %s 修改成功",id),
"code" : 200,
})
} else {
fmt.Println("修改失败")
c.JSON(http.StatusOK,gin.H{
"message" : fmt.Sprintf("id : %s 修改失败",id),
"code": 200,
})
}
}
func DeleteUser(c *gin.Context) {
id := c.PostForm("id")
stmt, err := dbs.MysqlDb.Prepare("delete from t_user where id=?")
if err != nil {
fmt.Println("err", err)
}
deleteUser, _ := stmt.Exec(id)
ins_nus, _ := deleteUser.RowsAffected()
if ins_nus > 0 {
fmt.Println("删除成功")
c.JSON(http.StatusOK, gin.H{
"message": "delete ok",
"code": fmt.Sprintf("删除id: %s", id),
})
} else {
fmt.Println("删除失败")
c.JSON(http.StatusOK, gin.H{
"message": "delete error",
"code": fmt.Sprintf("删除 id : %s 失败", id),
})
}
}