首先,在本地搭建好mysql 5.6环境,将数据库的root用户密码改为root,创建godb数据库,在godb中执行以下SQL语句生成两个数据表:
DROP TABLE IF EXISTS `post`;
CREATE TABLE `post` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) DEFAULT NULL,
`title` varchar(60) COLLATE utf8_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- ----------------------------
-- Records of post
-- ----------------------------
-- ----------------------------
-- Table structure for `user`
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(60) COLLATE utf8_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
第二步:创建一个beego项目,结构如下:
第三步:替换default.go代码:
package controllers
import (
"fmt"
"github.com/astaxie/beego"
"github.com/astaxie/beego/orm"
_ "github.com/go-sql-driver/mysql"
"quickstart/models"
)
type MainController struct {
beego.Controller
}
func (c *MainController) Get() {
c.Data["Website"] = "beego.me"
c.Data["Email"] = "astaxie@gmail.com"
c.TplName = "index.tpl"
}
func (c *MainController) TestOrm() {
o := orm.NewOrm()
user := models.User{Name: "slene"}
// insert
id, err := o.Insert(&user)
fmt.Printf("ID: %d, ERR: %v\n", id, err)
// update
//user.Name = "astaxie"
//num, err := o.Update(&user)
//fmt.Printf("NUM: %d, ERR: %v\n", num, err)
// read one
u := models.User{Id: 1}
err = o.Read(&u)
fmt.Printf("ERR: %v\n", err)
fmt.Println(u)
// delete
//num, err = o.Delete(&u)
//fmt.Printf("NUM: %d, ERR: %v\n", num, err)
c.Data["Website"] = "beego.me"
c.Data["Email"] = "astaxie@gmail.com"
c.TplName = "index.tpl"
}
第四步:替换models.go的代码:
package models
import "github.com/astaxie/beego/orm"
type User struct {
Id int
Name string `orm:"size(100)"`
}
type Post struct {
Id int `orm:"auto"`
Title string `orm:"size(100)"`
User *User `orm:"rel(fk)"`
}
func init() {
// set default database
orm.RegisterDataBase("default", "mysql", "root:root@tcp(127.0.0.1:3306)/godb?charset=utf8", 30)
// register model
orm.RegisterModel(new(User))
// create table
orm.RunSyncdb("default", false, true)
}
第五步,routs.go添加路由后代码如下:
package routers
import (
"github.com/astaxie/beego"
"quickstart/controllers"
)
func init() {
beego.Router("/", &controllers.MainController{})
beego.Router("/orm", &controllers.MainController{},"*:TestOrm")
}
OK,到Terminal面板执行命令:
bee run
最后如果出现如下图,则表示服务器已成功运行:
在浏览器输入:
http://localhost:8080/orm
此时出现界面
而Terminal面板出现类似
数据 表里也有数据插入成功,则此实例已成功运行了。