首页 > 数据库技术 > 详细

golang web框架 beego 学习 (四) 连接mysql

时间:2019-04-13 23:49:15      阅读:221      评论:0      收藏:0      [点我收藏+]

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:root@tcp(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

原文:https://www.cnblogs.com/liufei1983/p/10703350.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!