mysql.go 1.22 KB
package database

import (
	"encoding/json"
	_ "github.com/Go-SQL-Driver/MySQL"
	"github.com/lunny/xorm"
	"log"
	"os"
)

var Engine *xorm.Engine

type confInfo struct {
	Host     string
	Username string
	Password string
	Database string
}

func init() {
	var err error
	file, err := os.Open("./conf/conf.json")
	if err != nil {
		log.Println("配置文件打开错误!")
		log.Fatal(err)
	}
	defer file.Close()
	conf := confInfo{}
	decoder := json.NewDecoder(file)
	// str := `{"host":"rm-2zenjpu465r1ee1rd.mysql.rds.aliyuncs.com:3306","username":"icesimba_root","password":"Icesimba858680668866sdk121","database":"icesimbasdk_pro"}`
	err = decoder.Decode(&conf)
	if err != nil {
		log.Println("配置文件解析错误!")
		log.Fatal(err)
	}
	log.Printf("%+v", conf)
	//测试数据库
	// Engine, err = xorm.NewEngine("mysql", "trump:Trump123@(rm-2zenjpu465r1ee1rd.mysql.rds.aliyuncs.com:3306)/icesimbasdk_test?charset=utf8")
	//正式数据库
	Engine, err = xorm.NewEngine("mysql", conf.Username+`:`+conf.Password+`@(`+conf.Host+`)/`+conf.Database+`?charset=utf8`)
	if err != nil {
		log.Println("数据库连接错误")
		log.Fatal(err)
	}
	if err = Engine.Ping(); err != nil {
		log.Println("数据库连接失败")
		log.Fatal(err)
	}
}