版权声明:本文为博主原创文章,未经博主允许不得转载。 https://cloud.tencent.com/developer/article/1334450
beego普通的写操作很慢,大约200多ms一条。如下:
Insert
第一个返回值为自增健 Id 的值
o := orm.NewOrm()
var user User
user.Name = "slene"
user.IsActive = true
id, err := o.Insert(&user)
if err == nil {
fmt.Println(id)
}
修改的办法就是取消写同步:
o.Raw("PRAGMA synchronous = OFF; ", 0, 0, 0).Exec()
然后还用了原生的sql语句,用上面的insert语句效果也是一样的。建立4300条具有逻辑关系的数据,从19m变为6s多。
//递归将目录写入数据库
func Insertproj(pid []Pidstruct, nodes []*AdminCategory, igrade, height int) (cid []Pidstruct) {
o := orm.NewOrm() //实例化数据库操作对象
// o.Using("default")
//关闭写同步
o.Raw("PRAGMA synchronous = OFF; ", 0, 0, 0).Exec()
// var project models.Project
var Id int64
for _, v := range pid {
for _, v1 := range nodes {
if v1.Grade == igrade {
title := v1.Title
code := v1.Code
parentid := v.ParentId
var parentidpath string
var parenttitlepath string
if v.ParentIdPath != "" {
parentidpath = v.ParentIdPath + "-" + strconv.FormatInt(v.ParentId, 10)
parenttitlepath = v.ParentTitlePath + "-" + v.ParentTitle
} else {
parentidpath = strconv.FormatInt(v.ParentId, 10)
parenttitlepath = v.ParentTitle
}
grade := igrade
//通过事务方式来进行数据插入
// err := o.Begin()
sql := fmt.Sprintf("insert into Project (Code, Title, Label, Principal, Parent_id, Parent_id_path, Parent_title_path, Grade)"+
" values('%s','%s','%s','%s',%d,'%s','%s',%d)", code, title, "", "", parentid, parentidpath, parenttitlepath, grade)
res, err := o.Raw(sql).Exec()
if err != nil {
o.Rollback()
// beego.Info("插入t_studentInfo表出错,事务回滚")
} else {
// o.Commit()
// beego.Info("插入t_studenInfo表成功,事务提交")
// num, _ = res.RowsAffected()
Id, _ = res.LastInsertId()
}
// Id, err := models.AddProject(code, title, "", "", parentid, parentidpath, parenttitlepath, grade)
// if err != nil {
// beego.Error(err)
// }
var cid1 Pidstruct
cid1.ParentId = Id
cid1.ParentTitle = title
cid1.ParentIdPath = parentidpath
cid1.ParentTitlePath = parenttitlepath
cid = append(cid, cid1) //每次要清0吗?
}
}
}
igrade = igrade + 1
if igrade <= height {
Insertproj(cid, nodes, igrade, height)
}
return
}