添加orm操作

This commit is contained in:
朱毅骏 2021-07-13 17:33:56 +08:00
parent 24e1538ff4
commit e46a01c0fd
13 changed files with 300 additions and 1 deletions

View File

@ -1 +1,5 @@
root = root
root = root
password = 123456
host = localhost
port = 3306
db = beego

View File

@ -0,0 +1,104 @@
package test_orm
import (
"beego_demo1/models"
"github.com/astaxie/beego"
"github.com/astaxie/beego/orm"
"log"
)
type OrmController1 struct {
beego.Controller
}
func (c *OrmController1) Get() {
o := orm.NewOrm()
//默认是要default 也可以指定
//o.Using("default")
//user := models.User{Name: "逝水无痕",Age: 18,Addr: "武汉",Class: "二班"}
////插入数据库
//id,err := o.Insert(&user)
//if err != nil {
// log.Fatalln(err)
//}
//log.Println("添加一条数据id为:",id)
//删除
//count, err := o.Delete(&user)
//if err != nil {
// log.Fatalln(err)
//}
//log.Println("删除",count,"条数据")
//添加多条数据
//users := []models.User{{Name: "逝水无痕2",Age: 18,Addr: "武汉",Class: "二班"},
// {Name: "逝水无痕3",Age: 18,Addr: "武汉",Class: "二班"},
// {Name: "逝水无痕4",Age: 18,Addr: "武汉",Class: "二班"},
//}
////multi一次性插入多少条数据
//count, err := o.InsertMulti(10, &users)
//if err != nil {
// log.Fatalln(err)
// log.Fatalln("批量插入失败")
//}
//log.Println("插入",count,"条数据")
//查询
//user := models.User{Id:14}
//user := models.User{Id:14,Name:"逝水无痕2"}
////"Name" 跟结构体的Name保持一致
//err := o.Read(&user,"Name","Id")
//if err != nil {
// log.Println("查询失败",err)
//} else {
// log.Println(user)
//}
//user := models.User{Name: "逝水无痕5"}
//create, id, err := o.ReadOrCreate(&user, "Name")
//if err != nil {
// log.Println("查询失败", err)
//}
//log.Println(id, user, create)
/*
1如果没查到就添加一条 //17 {17 逝水无痕5 0 } true create为true
2如果有这查出来 //{17 逝水无痕5 0 } false create为false
*/
//update 指定条件更新
//user := models.User{Id: 14}
//err := o.Read(&user, "Id")
//if err != nil {
// log.Println("查询失败", err)
//} else {
// log.Println(user)
// user.Name = "逝水无痕"
// user.Age = 20
// user.Addr = "北京"
// count, err := o.Update(&user,"Name","Addr")
// if err != nil {
// log.Println("更新失败", err)
// }else {
// fmt.Println("更新了",count,"条数据")
// fmt.Println(user)
// }
//}
//先查询后删除
//user := models.User{Name:"逝水无痕5"}
//count, err := o.Delete(&user,"Name")
//if err != nil {
// log.Fatalln(err)
//}
//log.Println("删除",count,"条数据")
//InsertOrUpdate 没有则添加有则更新 User的Id必须添加 `orm:"pk"`
user := models.User{Id: 18, Name: "逝水无痕5", Age: 10, Addr: "广州", Class: "一班"}
id, err := o.InsertOrUpdate(&user, "Id")
if err != nil {
log.Fatalln(err)
}
log.Println("id为", id)
log.Println(user)
c.TplName = "test_orm/orm1.html"
}

View File

@ -0,0 +1,44 @@
package test_orm
import (
"beego_demo1/models"
"github.com/astaxie/beego"
"github.com/astaxie/beego/orm"
"github.com/prometheus/common/log"
)
type OrmController2 struct {
beego.Controller
}
type OrmController2Add struct {
beego.Controller
}
func (t *OrmController2) Get() {
o := orm.NewOrm()
article := models.Article{Id: 1}
err := o.Read(&article)
if err != nil {
log.Errorf("没有查到")
}
log.Info("查到数据", article)
t.Data["article"] = article
t.TplName = "test_orm/orm2_list.html"
}
func (t *OrmController2Add) Get() {
t.TplName = "test_orm/orm2_add.html"
}
func (t *OrmController2Add) Post() {
title := t.GetString("title")
author := t.GetString("author")
o := orm.NewOrm()
article := models.Article{Title: title, Author: author}
count, err := o.Insert(&article)
if err != nil {
log.Errorf("插入失败")
}
log.Info("插入", count, "条")
t.TplName = "success.html"
}

View File

@ -4,6 +4,8 @@ go 1.16
require (
github.com/astaxie/beego v1.12.3
github.com/go-sql-driver/mysql v1.6.0
github.com/prometheus/common v0.10.0
github.com/shiena/ansicolor v0.0.0-20200904210342-c7312218db18 // indirect
github.com/smartystreets/goconvey v1.6.4
golang.org/x/net v0.0.0-20201021035429-f5854403a974 // indirect

View File

@ -1,8 +1,10 @@
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/Knetic/govaluate v3.0.0+incompatible/go.mod h1:r7JcOSlj0wfOMncg0iLm8Leh48TZaKVeNIfJntJ2wa0=
github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751 h1:JYp7IbQjafoB+tBA3gMyHYHrpOtNuDiK/uB5uXxq5wM=
github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4 h1:Hs82Z41s6SdL1CELW+XaDYmOH4hkBN4/N9og/AsOv7E=
github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
github.com/alicebob/gopher-json v0.0.0-20180125190556-5a6b3ba71ee6/go.mod h1:SGnFV6hVsYE877CKEZ6tDNTjaSXYUk6QqoIK6PrAtcc=
github.com/alicebob/miniredis v2.5.0+incompatible/go.mod h1:8HZjEj4yU0dwhYHky+DxYx+6BMjkBbe5ONFIF1MXffk=
@ -39,6 +41,8 @@ github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V
github.com/go-redis/redis v6.14.2+incompatible/go.mod h1:NAIEuMOZ/fxfXJIrKDQDz8wamY7mA7PouImQ2Jvg6kA=
github.com/go-sql-driver/mysql v1.5.0 h1:ozyZYNQW3x3HtqT1jira07DN2PArx2v7/mN66gGcHOs=
github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg=
github.com/go-sql-driver/mysql v1.6.0 h1:BCTh4TKNUYmOmMUcQ3IipzF5prigylS7XXjEkfCHuOE=
github.com/go-sql-driver/mysql v1.6.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg=
github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
@ -69,6 +73,7 @@ github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/
github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo=
github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU=
github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w=
github.com/konsorten/go-windows-terminal-sequences v1.0.1 h1:mweAR1A6xJ3oS2pRaGiHgQ4OO8tzTaLawm8vnODuwDk=
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc=
github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
@ -98,6 +103,7 @@ github.com/peterh/liner v1.0.1-0.20171122030339-3681c2a91233 h1:jmJndGFBPjNWW+MA
github.com/peterh/liner v1.0.1-0.20171122030339-3681c2a91233/go.mod h1:xIteQHvHuaLYG9IFj6mSxM0fCKrs34IrEQUhOYuGPHc=
github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
@ -123,6 +129,7 @@ github.com/siddontang/go v0.0.0-20170517070808-cb568a3e5cc0/go.mod h1:3yhqj7WBBf
github.com/siddontang/goredis v0.0.0-20150324035039-760763f78400/go.mod h1:DDcKzU3qCuvj/tPnimWSsZZzvk9qvkvrIL5naVBPh5s=
github.com/siddontang/rdb v0.0.0-20150307021120-fc89ed2e418d/go.mod h1:AMEsy7v5z92TR1JKMkLLoaOQk++LVnOKL3ScbJ8GNGA=
github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
github.com/sirupsen/logrus v1.4.2 h1:SPIRibHv4MatM3XXNO2BJeFLZwZ2LvZgfQ5+UNI2im4=
github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE=
github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d h1:zE9ykElWQ6/NYmHa3jpm/yHnI4xSofP+UP6SpjHcSeM=
github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc=
@ -181,6 +188,7 @@ google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miE
google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo=
google.golang.org/protobuf v1.23.0 h1:4MY060fB1DLGMB/7MBTLnwQUY6+F09GEiz6SsrNqyzM=
google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
gopkg.in/alecthomas/kingpin.v2 v2.2.6 h1:jMFz6MfLP0/4fUyZle81rXUoxOBFi19VUFKVDOQfozc=
gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=

View File

@ -4,8 +4,26 @@ import (
_ "beego_demo1/routers"
"fmt"
"github.com/astaxie/beego"
"github.com/astaxie/beego/orm"
_ "github.com/go-sql-driver/mysql"
)
func init() {
/*
1注册驱动
2注册数据库连接
*/
root := beego.AppConfig.String("root")
password := beego.AppConfig.String("password")
host := beego.AppConfig.String("host")
port := beego.AppConfig.String("port")
db := beego.AppConfig.String("db")
//"root:123456@tcp(localhost:3306)/beego?charset=utf8"
data_source := root + ":" + password + "@tcp(" + host + ":" + port + ")/" + db + "?charset=utf8"
orm.RegisterDriver("mysql", orm.DRMySQL)
orm.RegisterDataBase("default", "mysql", data_source)
}
func main() {
//设置views路径
//beego.SetViewsPath("front")

View File

@ -0,0 +1,35 @@
package models
import "github.com/astaxie/beego/orm"
/**
代表忽略 `orm:"-"`
*/
type User struct {
Id int `json:"id" orm:"pk"`
Name string `json:"name" orm:"column(name)"`
Age int `json:"age" orm:"column(age)"`
Addr string `json:"addr" orm:"column(addr)"`
Class string `json:"clazz" orm:"column(clazz)"`
}
/**
1默认表面以大写字母分割中间加下划线,首字母的大写只转换为小写前面不加下划线
SysUser -> sys_user
DBUser -> d_b_user
Sys_User -> sys__user
重写表名
*/
//func (u * User) TableName() string {
// return "sys_user"
//}
func init() {
//需要放在init下 注册models
orm.RegisterModel(new(User))
/*
//前缀
orm.RegisterModelWithPrefix("sys",new(User))
//后缀
orm.RegisterModelWithSuffix("sys",new(User))
*/
}

View File

@ -0,0 +1,16 @@
package models
import "github.com/astaxie/beego/orm"
type Article struct {
Id int `orm:"pk"`
Title string `orm:"title"`
Author string `orm:"author"`
}
func (a *Article) TableName() string {
return "article"
}
func init() {
orm.RegisterModel(new(Article))
}

View File

@ -2,6 +2,7 @@ package routers
import (
"beego_demo1/controllers"
"beego_demo1/controllers/test_orm"
"github.com/astaxie/beego"
)
@ -32,4 +33,8 @@ func init() {
beego.Router("/template1", &controllers.TemplateController{})
//模板函数
beego.Router("/template2", &controllers.Template2Controller{})
beego.Router("/orm1", &test_orm.OrmController1{})
beego.Router("/article", &test_orm.OrmController2{})
beego.Router("/article/add", &test_orm.OrmController2Add{})
}

View File

@ -52,11 +52,20 @@
{{urlquery "http://www.baidu.com"}}
<br>
<!--
eq 等于
ne 不等于
lt 小于
le 小于等于
gt 大于
ge 大于等于
-->
{{eq 2 3}}
{{ne 2 3}}
{{lt 2 4}}
{{le 3 3}}
{{gt 4 2}}
{{ge 4 4}}
{{eq 3 5 6}}
</body>
</html>

View File

@ -0,0 +1,10 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ORM</title>
</head>
<body>
<h1>orm使用</h1>
</body>
</html>

View File

@ -0,0 +1,16 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>文章添加页面</title>
</head>
<body>
<h1>文章添加页面</h1>
<form action="/author/add" method="post">
{{.xsrf}}
<input type="text" name="title"><br>
<input type="text" name="author"><br>
<input type="submit" value="提交">
</form>
</body>
</html>

View File

@ -0,0 +1,28 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>文章列表</title>
</head>
<body>
<h1>文章列表</h1>
<a href="">添加</a> <br>
<table>
<thead>
<th>编号</th> &nbsp;&nbsp;
<th>标题</th> &nbsp;&nbsp;
<th>作者</th>&nbsp;&nbsp;
</thead>
<tr>
{{if .article.Id}}
<td>{{.article.Id}}</td> &nbsp;&nbsp;
<td>{{.article.Title}}</td> &nbsp;&nbsp;
<td>{{.article.Author}}</td> &nbsp;&nbsp;
<td><a href="">修改</a></td> &nbsp;&nbsp;
<td><a href="">删除</a></td>&nbsp;&nbsp;
{{end}}
</tr>
</table>
</body>
</html>