Skip to main content

数据库查询

[toc]

查询列表数据

Values

返回结果集的 key => value 值

func GetVideoListRowList()   (vl []orm.Params,err error) {
var o = orm.NewOrm()
var maps []orm.Params
num, err := o.QueryTable("video_list").Values(&maps)
if err == nil {
fmt.Printf("Result Nums: %d\n", num)
for _, m := range maps {
fmt.Println(m["Id"], m["Name"])
}
}
return maps,nil
}

查询列表的例子 ValuesList

结果中不带字段名的,不包含key

func GetVideoListRowList()   (vl []orm.ParamsList,err error) {
var o = orm.NewOrm()
var lists []orm.ParamsList
num, err := o.QueryTable("video_list").Limit(2,1).ValuesList(&lists,"author","play_cnt")
if err == nil {
fmt.Printf("Result Nums: %d\n", num)
for _, row := range lists {
fmt.Println(row)
}
}
return lists,nil
}

返回对应的结果集对象

也是返回结果集的 key => value 值

func GetVideoListRowList()   (vl []VideoList,err error) {
var o = orm.NewOrm()
num, err := o.QueryTable("video_list").Limit(2,1).All(&vl)
if err == nil {
fmt.Printf("Result Nums: %d\n", num)
fmt.Printf("Result Nums: %d\n", vl)
}
return
}

查询单条数据

func GetVideoListRow()   (vl VideoList,err error) {
o := orm.NewOrm()
vl = VideoList{Id: 1}
err = o.Read(&vl)
if err != nil{
fmt.Println(vl,nil)
}
return
}
func GetVideoListRow()   (vl VideoList,err error) {
var o = orm.NewOrm()
//Filter 中是匹配的条件,即使有多条,也会返回1条。
err = o.QueryTable("video_list").Filter("title","1dd12").One(&vl)
if err == orm.ErrMultiRows {
// 多条的时候报错
fmt.Printf("Returned Multi Rows Not One")
}
if err == orm.ErrNoRows {
// 没有找到记录
fmt.Printf("Not row found")
}
return
}