您的位置 首页 golang

golang通过mysql语句实现分页查询

1.前端接口调用

golang通过mysql语句实现分页查询

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)
}  
golang通过mysql语句实现分页查询

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语句实现分页查询

查询语句加上参数。控制查到的页数。

golang通过mysql语句实现分页查询


返回的是总数量跟当前查询页。

特殊情况用不到数据库分页的,就需要用到内存分页了.

文章来源:智云一二三科技

文章标题:golang通过mysql语句实现分页查询

文章地址:https://www.zhihuclub.com/98530.shtml

关于作者: 智云科技

热门文章

评论已关闭

52条评论

  1. A Comparison of dark neuron numbers per area in DG between control, Sham PTZ, DNA Cell Biol 2005; 24 4 244 255

  2. Ergotamine Tartrate Although ergotamine is usually considered to be a migraine abortive, it is occasionally helpful as a preventive for certain forms of migraine or cluster headache

  3. Among the promising bioactive food components being investigated at the National Cancer Institute in prevention clinical trials to reduce breast cancer risk are indole 3 carbinol, sulforaphanes, phytoestrogen isoflavones, perillyl alcohol, and green tea polyphenols

  4. Harvey Himel, Joseph Fisher Debra, and Louisa Rudolph James, five grandchildren and two great grandchildren

  5. last time flying Alaska 1 Several of the known risk factors for breast cancer are associated with estrogen exposure, namely early menstruation, late menopause, late or no pregnancy, and use of oral contraceptives or hormone replacement therapy

  6. FLPe codon optimization resulted in FLPO, which shows similar efficiency to Cre Kranz et al

  7. There appear to be two major types of breast cancer related defects in thermoregulation 1 excessive, rapid overheating, similar to that which occurs with the vasomotor symptoms associated with menopause i

  8. You also want your organic maca to be from Peru versus somewhere else, as that will also ensure it is GMO free The Peruvian government currently bans GMO in maca harvests Smith Center for Women s Cancers at Dana Farber, explained tamoxifen taken for five years has been the standard adjuvant hormonal treatment for decades, but we now have evidence to recommend up to 10 years of tamoxifen for women with hormone receptor positive breast cancer

  9. Unlike measuring lipids for heart disease risk, there is no available serum marker for increased breast cancer risk

  10. Here we showed that in a time dependent manner, metformin increased p AMPK and decreased p mTOR expression

  11. Strikingly, the proportion of marked cells within the transplanted and the in vivo remaining HSC compartment was not different, implying that no further HSC generation occurred during late fetal and neonatal stages of development

  12. Digite seu endereço de e mail para assinar este blog e receber notificações de novas publicações por e mail

  13. Over time, STAR suppression ceased, allowing for induction of STAR activity and increased rate of steroid formation

  14. A single focal plane across the middle of the nucleus marked by DAPI is shown Sucralfate, cholestyramine, and colestipol can decrease the absorption of Vergonil

  15. Midea, and other smaller technology companies have invested more than 500 million yuan, and some less than 100 to 200 million yuan

  16. Cell proliferation was measured after seven days using a fluorescence assay wherein emission at 535 nm is proportional to cell number

  17. I just stopped the shot I know, it took way too long to discover the real problem but NO medical professional would even consider the link

  18. The activity of sequential endocrine therapies is dependent upon them possessing different mechanisms of action Here, tumorigenesis was defined when obvious hyperplasic tissues were observed

  19. If you have mild acne, it may improve with topical treatments purchased over the counter

  20. Finding your blog has been very helpful to me my Dr sent me home Friday with Misoprostol for my missed miscarriage we were 9 weeks along when we discovered his amniotic sac was empty w no heartbeat on Friday

  21. Disease free survival DFS was defined as the period from the date of surgery to that of recurrence or death, and was calculated by the Kaplan Meier method I am sure this has been discussed a lot but just wanted to get an update on what everyone is using to keep the balls in check since HCG is nearly impossible to get

  22. 0 mg and may be given once or twice per day Serum TSH showed greater between sample variation for each individual than serum T4 or T3

  23. Ideally though, capitalist policies together with certain regulations, are the best proven policies everywhere in the world Nexus Pharmaceuticals Northstar Rx LLC Novartis AG Novex Pharma Nucare Pharmaceuticals Inc

  24. However, good agreement regarding ER and PR status between these methods has been reported, and the pooling of the data would therefore have only a minor influence on the results

  25. Diabetic foot ulcers can occur at any age but are most prevalent in patients with diabetes mellitus ages 45 and over

  26. You are wrong, the scorpion has just broken the seal, and his testosterone to increase libido strength is at its weakest

  27. The information provided in Special warnings and precautions for use of Genox is based on data of another medicine with exactly the same composition as the Genox The effect of increasing end diastolic ventricular volume EDV on stroke volume is plotted in Fig

  28. Does the mast cell have an intrinsic role in the pathogenesis of interstitial cystitis

  29. 2000 Sep; 57 9 841 9 Discontinue cefazolin injection if seizures occur or make appropriate dosage adjustments in patients with renal impairment

  30. Moreover, improved imaging and recording methods may help address the heterogeneity of brain disorders by identifying brain activity changes associated with disease states in a single individual, creating a truly personalized brain medicine

  31. It is not the drug of choice for tetanus but may be used when the drugs of choice cannot be administered for some reason In addition to ABC s award winning content, KLAX delivers a variety of top rated syndicated programming, and local news, weather and sports through ABC 31 News

  32. It begins as an area of vasculitic inflammation subjacent to the tunica albuginea and progresses to focal fibrous thickening of the tunica that may extend into the intercavernosal septum

  33. 121, 459 488 2011 They can also prevent pathogenicity by interfering with signaling between pathogens by degrading quorum sensing molecules 17

  34. As suggested, patients with AKI fluid overload, hypoxia, and on mechanical ventilation actually may not have ARDS

  35. After 1 h, blood samples were taken again for turnover measurements and the rats were sacrificed as described above

  36. If the cheaper biomarker is 2000, then choosing biomarker 2 at the interim analysis reduces the cost of testing by 44 from 7 200 000 to 3 900 000 3 Viruses manipulate autophagy to promote their replication

网站地图