golang web框架 beego 学习 连接mysql

Posted 刘大飞

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了golang web框架 beego 学习 连接mysql相关的知识,希望对你有一定的参考价值。

1 DB参数配置在app.conf

appname = gowebProject
httpport = 8080
runmode = dev


[db]
host= localhost
port= 3306
databaseName = test
userName= root
password= root

2 模型定义在Models.go中

package models

import (
    "fmt"
    "time"

    "github.com/astaxie/beego"
    "github.com/astaxie/beego/orm"
)

type Store struct {
    Id              int64
    Title           string
    Created         time.Time `orm:"index"`
    Views           int64     `orm:"index"`
    TopicTime       time.Time `orm:"index"`
    TopicCount      int64
    TopicLastUserId int64
}

type Customer struct {
    Id              int64
    Uid             int64
    Title           string
    Content         string `orm:"size(5000)"`
    Attachment      string
    Created         time.Time `orm:"index"`
    Updated         time.Time `orm:"index"`
    Views           int64     `orm:"index"`
    Author          string
    ReplyTime       time.Time `orm:"index"`
    ReplyCount      int64
    ReplyLastUserId int64
}

func RegisterDB() {
    //注册 model
    orm.RegisterModel(new(Store), new(Customer))
    //注册驱动
    orm.RegisterDriver("mysql", orm.DRMySQL)
    //注册默认数据库
    host := beego.AppConfig.String("db::host")
    port := beego.AppConfig.String("db::port")
    dbname := beego.AppConfig.String("db::databaseName")
    user := beego.AppConfig.String("db::userName")
    pwd := beego.AppConfig.String("db::password")

    dbcon := user + ":" + pwd + "@tcp(" + host + ":" + port + ")/" + dbname + "?charset=utf8"
    fmt.Print(dbcon)
    orm.RegisterDataBase("default", "mysql", dbcon /*"root:[email protected](localhost:3306)/test?charset=utf8"*/) //密码为空格式
}

3  main

package main

import (
    _ "gowebProject/routers"

    "github.com/astaxie/beego"

    // "fmt"
    "gowebProject/models"

    "github.com/astaxie/beego/orm"

    _ "github.com/go-sql-driver/mysql"
)

//引入数据模型
func init() {
    // 注册数据库
    models.RegisterDB()
}

func main() {
    // 开启 ORM 调试模式
    orm.Debug = true
    // 自动建表
    orm.RunSyncdb("default", false, true)
    // 运行时
    beego.Run()
}

 

以上是关于golang web框架 beego 学习 连接mysql的主要内容,如果未能解决你的问题,请参考以下文章

golang web框架 beego 学习 配置文件

golang 都有哪些比较稳定的 web 开发框架

golang框架对比Revel and Beego

golang框架对比Revel and Beego

Golang入门教程beego 快速开发 HTTP 框架

beego框架(golang)学习过滤器(实现restful请求)