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 }