data_source
package data_source
import (
"fmt"
"gin_project/models"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
)
var Db *gorm.DB
var err error
func init() {
fmt.Println("初始化init")
//Db,err = gorm.Open("mysql","root:123456@tcp(localhost:3306)gin_project?charset=utf8&parseTime=true&loc=Local")
Db,err = gorm.Open("mysql","root:123456@/gin_project?charset=utf8&parseTime=True&loc=Local")
if err !=nil {
panic(err)
}
//defer Db.Close()
Db.Create(&models.User{Name: "lin",Age: 32})
Db.DB().SetMaxOpenConns(100) // 最大连接数
Db.DB().SetMaxIdleConns(50) // 最大空闲数
Db.AutoMigrate(&models.User{})
}
在main.go引入
_ "gin_project/data_source"
方法
package chapter06
import (
"gin_project/data_source"
"gin_project/models"
"github.com/gin-gonic/gin"
)
func GormTest(ctx *gin.Context) {
user := models.User{Name: "LIN",Age: 32}
data_source.Db.Create(&user)
data_source.Db.Close()
}
mysql配置文件
一、配置信息:mysql.json
{
"host":"localhost",
"port":"3306",
"user_name":"root",
"password":"Qazwsx123",
"database":"gin_project",
"logo_mode":true
}
二、加载配置文件
package data_source
import (
"os"
"io/ioutil"
"encoding/json"
)
type MysqlConf struct {
Host string `json:"host"`
Port string `json:"port"`
UserName string `json:"user_name"`
Password string `json:"password"`
DataBase string `json:"database"`
LogoMode bool `json:"logo_mode"`
}
func LoadMysqlConf() *MysqlConf {
mysql_conf := MysqlConf{}
file,err := os.Open("conf/mysql.json")
if err != nil {
panic(err)
}
defer file.Close()
byte_data,err2 := ioutil.ReadAll(file)
if err2 != nil {
panic(err2)
}
err3 := json.Unmarshal(byte_data,&mysql_conf)
if err3 != nil {
panic(err3)
}
return &mysql_conf
}
三、使用配置信息
package data_source
import (
"github.com/jinzhu/gorm"
"gin_project/models"
_ "github.com/jinzhu/gorm/dialects/mysql"
"fmt"
)
var Db *gorm.DB
var err error
func init() {
mysql_conf := LoadMysqlConf()
logo_mode := mysql_conf.LogoMode
data_source := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=true&loc=Local",
mysql_conf.UserName,
mysql_conf.Password,
mysql_conf.Host,
mysql_conf.Port,
mysql_conf.DataBase,
)
Db,err = gorm.Open("mysql",data_source)
if err != nil {
panic(err)
}
Db.LogMode(logo_mode)
Db.DB().SetMaxOpenConns(100) // 最大连接数
Db.DB().SetMaxIdleConns(50) // 最大空闲数
Db.AutoMigrate(&models.User{})
}