Gin 框架mysql的連接搭建


 

Gin框架中mysql的連接

安裝驅動

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

安裝Gorm

go get -u github.com/jinzhu/gorm

 

package main

import (
    "fmt"
    "github.com/gin-gonic/gin"
    _ "github.com/go-sql-driver/mysql"
    "github.com/jinzhu/gorm"
    "net/http"
    "time"
)

type User struct {
    gorm.Model
    Name      string `gorm:"type:varchar(20);not null"`
    Telephone string `gorm:"varchar(20);not null;unique"`
    Password  string `gorm:"size:255;not null"`
}

//項目初始化
func main() {
    db := InitDB()
    defer db.Close() //延時關閉

    r := gin.Default()

    //r.Run()
    panic(r.Run()) // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}


//數據庫連接
func InitDB() *gorm.DB {

    driverName := "mysql"
    host := "127.0.0.1"
    port := "3306"
    database := "blog"
    username := "root"
    password := "islot"
    charset := "utf8"
    args := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=true",
        username,
        password,
        host,
        port,
        database,
        charset,
    )

    db, err := gorm.Open(driverName, args)
    //db, err := gorm.Open("mysql", "user:islot@/blog?charset=utf8&parseTime=True&loc=Local")
    if err != nil {
        panic("failed to connect database,err:" + err.Error())
    }

    //自動創建數據表
    db.AutoMigrate(&User{})

    return db

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM