BeegoOrm

package orm

import (
    "fmt"
    "github.com/astaxie/beego/config"
    "github.com/astaxie/beego/orm"
    // 加载MySQL驱动
    _"github.com/go-sql-driver/mysql"
)

type MysqlConfig map[string]string ;

/**
 * 获取配置项
 */
func (retval *MysqlConfig) GetConfig(){
    const file_name string = "./conf/mysql.conf" ;
    const file_type string = "ini" ;
    iniconf ,err := config.NewConfig(file_type,file_name)
    if err != nil {
        // 获取配置项失败 直接返回错误
        panic("Thrown exception:Mysql 配置文件不存在 filePath ./config/mysql.config");
    }
    (*retval)["host"] = iniconf.String("host") ;
    (*retval)["port"] = iniconf.String("port") ;
    (*retval)["username"] = iniconf.String("username") ;
    (*retval)["password"] = iniconf.String("password") ;
    (*retval)["dbname"] = iniconf.String("dbname") ;
    (*retval)["charset"] = iniconf.String("charset") ;
}

/**
 * 获取处理过后的DSN
 */
func GetDns() string {
    // 获取数据配置项
    myIniConfig  := make(MysqlConfig);
    myIniConfig.GetConfig()
    return fmt.Sprintf("%v:%v@tcp(%v:%v)/%v?charset=%v",
        myIniConfig["username"],
        myIniConfig["password"],
        myIniConfig["host"],
        myIniConfig["port"],
        myIniConfig["dbname"],
        myIniConfig["charset"]);
}

func init(){
    dns := GetDns();
    // 注册MySQL 驱动
    RegisterDriverErr := orm.RegisterDriver("mysql",orm.DRMySQL);
    // 注册 Mysql 数据库 * 连接
    RegisterDataBaseErr := orm.RegisterDataBase("default", "mysql",dns)
    // 判断 连接操作是否存在问题
    if RegisterDriverErr != nil || RegisterDataBaseErr!= nil {
        // 抛出异常
        panic(fmt.Sprintf("Thrown exception:for RegisterDriverErr : %v , RegisterDataBaseErr : %v",fmt.Sprintf("%s", RegisterDriverErr) , fmt.Sprintf("%s", RegisterDataBaseErr)));
    }
    fmt.Println("数据库连接 :SUCCESS");
}