## 一、在main.go中调用RunCommand命令
~~~
beego.Run()命令之前调用:
orm.RunCommand()
~~~
## 二、在程序中调用直接自动建表
~~~
name := "default"
// drop table 后再建表
force := false
// 打印执行过程
verbose := true
// 遇到错误立即返回
err := orm.RunSyncdb(name, force, verbose)
if err != nil {
fmt.Println(err)
}
~~~
## 三、实例
~~~
package main
import (
_ "beego_model02/models"
_ "beego_model02/routers"
"beego_model02/utils"
"fmt"
"github.com/astaxie/beego"
"github.com/astaxie/beego/orm"
_ "github.com/go-sql-driver/mysql"
)
func init() {
// 读取配置信息
dbhost := beego.AppConfig.String("dbhost")
dbport := beego.AppConfig.String("dbport")
dbuser := beego.AppConfig.String("dbuser")
dbpassword := beego.AppConfig.String("dbpassword")
db := beego.AppConfig.String("db")
//注册mysql Driver
orm.RegisterDriver("mysql", orm.DRMySQL)
//构造conn连接
//用户名:密码@tcp(url地址)/数据库
conn := dbuser + ":" + dbpassword + "@tcp(" + dbhost + ":" + dbport + ")/" + db + "?charset=utf8"
//注册数据库连接
orm.RegisterDataBase("default", "mysql", conn)
fmt.Printf("数据库连接成功!%s\n", conn)
}
func main() {
name := "default"
// drop table 后再建表
force := false
// 打印执行过程
verbose := true
// 遇到错误立即返回
err := orm.RunSyncdb(name, force, verbose)
if err != nil {
fmt.Println(err)
}
orm.RunCommand()
beego.Run()
}
~~~
## 四、报错
```
must have one register DataBase alias named `default`
```
确定下main.go中是否引入如下两个文件:
~~~
"github.com/astaxie/beego/orm"
_ "github.com/go-sql-driver/mysql"
~~~