golang web框架 beego 學習 (四) 鏈接mysql

1 DB參數配置在app.confmysql

appname = gowebProject
httpport = 8080
runmode = dev


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

2 模型定義在Models.go中git

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:root@tcp(localhost:3306)/test?charset=utf8"*/) //密碼爲空格式
}

3  maingithub

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()
}
相關文章
相關標籤/搜索