zoukankan      html  css  js  c++  java
  • 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: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()
    }
  • 相关阅读:
    网络
    分区
    JavaScript概述
    CSS样式属性
    css选择器
    CSS的引入方式
    css介绍
    HTML结构
    常用标签
    HTML介绍
  • 原文地址:https://www.cnblogs.com/liufei1983/p/10703350.html
Copyright © 2011-2022 走看看