- 引用连接库
- 声明一个DB变量,和err变量
- 使用init 函数自动连接
- 从app.conf中获取连接字段
- 建立连接
- 使用引用DB连接 数据库进行增删改查操作
import (
"fmt"
"github.com/astaxie/beego"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
)
var DB *gorm.DB
var err error
func init() {
sqlconn := beego.AppConfig.String("sqlconn")
mysqlPort := beego.AppConfig.String("mysqlPort")
mysqlAdmin := beego.AppConfig.String("mysqlAdmin")
mysqlpwd := beego.AppConfig.String("mysqlpwd")
mysqldb := beego.AppConfig.String("mysqldb")
DB,err = gorm.Open("mysql",fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=True&loc=Local", mysqlAdmin, mysqlpwd, sqlconn,mysqlPort, mysqldb))
if err != nil {
beego.Error(err)
}
DB.LogMode(true)
}