首頁 > 軟體

golang通過mysql語句實現分頁查詢

2022-03-25 13:01:03

1.前端介面呼叫

2.register存取入口

//查詢一個使用者下所有的subnet
ws.Route(ws.GET("/subnets").
To(sc.ListSubnet).
Doc("List subnets authorized to the login user.").
Param(ws.QueryParameter(query.ParameterPage, "page").Required(false).DataFormat("page=%d").DefaultValue("page=1")).
Param(ws.QueryParameter(query.ParameterLimit, "limit").Required(false)).
Returns(http.StatusOK, api.StatusOK, api.ListResult{}))

3.解析引數

//查詢某個使用者下所有的subnet資訊
func (v *SubController) ListSubnet(request *restful.Request, response *restful.Response) {
username := request.Attribute(filters.UserName).(string)

subnetService := &service.SubnetService{}
query := query.ParseQueryParameter(request)
result, err := subnetService.ListSubnet(query, v.Db, username)
if err != nil {
api.HandleError(response, request, err)
return
}
response.WriteEntity(result)
}

4.service實現

//查詢一個使用者所有的subnet資訊
func (ss *SubnetService) ListSubnet(query *query.Query, db *sql.DB, userName string) (*api.ListResult, error) {
sm := mapper.NewSubnetMapper(db)
sb, err := sm.SearchAllByUserName(query, userName)
return sb, err
}

5.mapper實現

//查詢使用者下的所以資訊
func (s *SubnetMapper) SearchAllByUserName(query *query.Query, userName string) (*api.ListResult, error) {

totalRow, err := s.Db.Query("SELECT COUNT(*) from t_subnet ,t_vpc where t_vpc.id = t_subnet.vpcid and username = ?", userName)
if err != nil {
klog.Error("query orders count error", err)
return nil, err
}
total := 0
for totalRow.Next() {
err := totalRow.Scan(
&total,
)
if err != nil {
klog.Error("query orders count error", err)
continue
}
}
totalRow.Close()

rows, err := s.Db.Query(SearchAllByUserNameSql, userName, query.Pagination.Limit, query.Pagination.Offset)
defer func() {
if rows != nil {
rows.Close()
}
}()
if err != nil {
klog.Error("query subnet error", err)
return nil, err
}
items := make([]interface{}, 0)
for rows.Next() {
ss := new(vpc.SubnetItem)
err = rows.Scan(&ss.VpcName, &ss.VpcNetwork, &ss.SubnetName, &ss.SubnetNetwork, &ss.CreateTime)
items = append(items, *ss)
}
return &api.ListResult{
TotalItems: total,
Items: items,
}, nil
}

可以看到第一步查出了所有count數目:

查詢語句加上引數。控制查到的頁數。

返回的是總數量跟當前查詢頁。

特殊情況用不到資料庫分頁的,就需要用到記憶體分頁了,下期小編給大家講解記憶體分頁。

到此這篇關於golang通過mysql語句實現分頁查詢的文章就介紹到這了,更多相關mysql實現分頁查詢內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com