join_mark

 

Go语言gin框架,简单实现书箱的增删查功能

目录结构

 

 

 

准备工作

创建一下数据库,新增一个表,插入两行数据

CREATE DATABASE libary;
CREATE TABLE `book` (
  `id` int(50) NOT NULL AUTO_INCREMENT,
  `title` varchar(50) DEFAULT NULL,
  `price` int(50) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
MariaDB [(none)]> USE libary
MariaDB [libary]> insert into book(id,title,price) VALUES(1,'C',50); 
MariaDB [libary]> insert into book(id,title,price) VALUES(2,'go',100); 
MariaDB [libary]> insert into book(id,title,price) VALUES(3,'python',150);
​

 

  • model.go

package model
type Book struct {
    ID int64 `db:"id"`
    Title string `db:"title"`
    Price int64 `db:"price"`
​
}

 

  • db.go

package db
import (
​
    "fmt"
    "github.com/jmoiron/sqlx"
    _ "github.com/go-sql-driver/mysql"  //init()
    "book/model"
​
​
)
//go连接mysql示例
var db *sqlx.DB   //是一个连接池对象
​
​
func InitDB()(err error){
    //数据库信息
    dsn := "book:book@tcp(10.0.0.90:3306)/libary"
    //连接数据库
    db,err = sqlx.Connect("mysql",dsn) //不会检验用户名和密码是否正确
if err != nil{
​
        return err
    }
    err = db.Ping() //尝试连接数据库
    if err != nil {
​
        return
    }
​
    db.SetMaxOpenConns(10) //设置数据库连接池最大连接数
    db.SetMaxIdleConns(5)  //设置最大空闲连接数
    return
}
​
// 查询所有记录
func QueryAllBook()(booklist []*model.Book,err error){
​
    //1.写查询单条记录的sql语句
    sqlStr :=`select id,title,price from book;`
    err =db.Select(&booklist,sqlStr)
    if err !=nil{
        fmt.Println("查询失败")
        return
    }
    return
}
func AddBook(title string,price string)(booklist []*model.Book,err error){
​
    //1.写查询单条记录的sql语句
    sqlStr :=`insert into book (title,price)VALUE (?,?);`
    _,err = db.Exec(sqlStr, title, price)
    if err !=nil{
        fmt.Println("插入失败")
        return
    }
    return
}
​
///book/delete
​
func DelBook(id string)(booklist []*model.Book,err error){
​
    //1.写查询单条记录的sql语句
    sqlStr :=`delete from book where id=?;`
    _,err = db.Exec(sqlStr,id)
    if err !=nil{
        fmt.Println("删除失败")
        return
    }
    return
}
 

 

  • main.go

package main
​
import (
    "book/db"
    "fmt"
    _ "github.com/go-sql-driver/mysql"  //init()
    "github.com/gin-gonic/gin"
    "net/http"
)
​
​
func main(){
​
    err := db.InitDB()
    if err !=nil{
        fmt.Printf("init DB failed,err:%v\n",err)
    }
    fmt.Println("连接数据库成功!")
​
    r := gin.Default()
    r.LoadHTMLGlob("../templates/*")
    r.GET("/book_list", func(c *gin.Context) {
        dataAll,err := db.QueryAllBook()
        if err !=nil{
            fmt.Printf("get data failed:err",err)
        }
            c.HTML(http.StatusOK,"book_list.html",gin.H{"data":dataAll})
    })
//添加新书
    r.GET("/book/new", func(c *gin.Context) {
        c.HTML(200,"new_book.html",nil)
    })
    r.POST("/book/new", func(c *gin.Context) {
        tile := c.PostForm("title")
        price := c.PostForm("price")
        db.AddBook(tile,price)
        //c.String(http.StatusOK,"add book successful!")
        c.Redirect(http.StatusMovedPermanently,"/book_list")
    })
​
    //删除书箱
    r.GET("/book/delete", func(c *gin.Context) {
        id := c.Query("id")
        db.DelBook(id)
        c.String(http.StatusOK,"delete book successful!")
    })
​
​
    r.Run(":8999")
​
}

 


 

  • templates

    book_list.html

    {{define "book_list.html"}}
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>书籍列表</title>
    </head>
    
    <body>
        <div><a href="/book/new">添加新书</a></div>
        <table border="1">
    
            <thead>
            <tr>
                <th>Id</th>
                <th>title</th>
                <th>price</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody>
    
            {{range .data}}
                <tr>
                    <td>{{.id}}</td>
                    <td>{{.title}}</td>
                    <td>{{.price}}</td>
                    <td><a href="/book/delete?id={{.id}}">删除</a></td>
                </tr>
                    {{end}}
            </tbody>
        </table>
    </body>
    </html>
    {{end}}

     

     

    new_book.html

    {{define "new_book.html"}}
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>添加图书信息</title>
    </head>
    <body>
    <form action="/book/new" method="post">
        <div>
            <label for="">书名:
                <input type="text" name="title">
            </label>
        </div>
        <div>
            <label for="">价格:
                <input type="number" name="price">
            </label>
        </div>
        <div>
            <input type="submit" value="提交">
        </div>
    </form>
    </body>
    </html>
    {{end}}

     

  • 浏览器访问

 

posted on 2020-11-13 20:20  join_mark  阅读(470)  评论(0)    收藏  举报

导航