以MySQL为例,先**安装驱动**
地址:https://github.com/go-sql-driver/mysql
命令:
~~~
go get -u github.com/go-sql-driver/mysql
~~~
**main.go**
> 需要注意的是struct的key首字母需要大写
~~~
package main
import (
_ "beego_blog/routers"
"fmt"
"github.com/astaxie/beego"
"github.com/astaxie/beego/orm"
_ "github.com/go-sql-driver/mysql"
)
type Article struct {
Id int
Author string
Content string
Create_time int
}
func main() {
orm.Debug = true
orm.RegisterModel(new(Article)) // 注册模型
orm.RegisterDriver("mysql", orm.DRMySQL) // 注册数据库驱动
orm.RegisterDataBase("default", "mysql", "root:root@/test?charset=utf8") // 默认数据库+用户名:密码/数据库名和字符集
o := orm.NewOrm()
article := Article{Id: 4}
err := o.Read(&article) // 读取id为4的数据
if err == orm.ErrNoRows {
fmt.Println("查询不到")
} else if err == orm.ErrMissPK {
fmt.Println("找不到主键")
} else {
fmt.Println(article)
}
beego.Run()
}
~~~