SQL select 查询的循环结果
时间:2024-04-17
浏览:199
作者:佚名
今日不肯埋头,明日何以抬头!每日一句努力自己的话哈哈~哈喽,今天我将给大家带来一篇《SQL select 查询的循环结果》,主要内容是讲解等等,感兴趣的朋友可以收藏或者有更好的建议在评论提出,我都会认真看的!大家一起进步,一起学习!
问题内容
我正在学习 go - 语言 atm 我仍然对执行查询时如何迭代从 sql 获得的数组列表感到困惑
这里是详细信息
我有一个名为customerdao.go的文件 其中包含一堆查询,我现在使用的查询是
select mst_customer.mcus_mlok_pk , mst_customer.mcus_mlok_kode , mst_customer.mcus_nama from frontend.mst_customer;
它将返回 50 行数据和 3 列,是吗? 现在令人困惑的部分是当我到达控制器时 就像这样
func GetArrayListCustomer(queryType string) (map[string]CustomerModelResponse, error) {
logger := customlogger.GetInstance()
logger.Println("Service: GetArrayListCustomer Start")
queryText := dao.CustomerDAO(queryType)
res, err := config.GetDbByPath("myDatabase").GetDb().Query(queryText)
mapList := make(map[string]CustomerModelResponse)
var custResponse CustomerModelResponse
if config.FancyHandleError(err) {
logger.Println("Service: GetArrayListCustomer -> Error " + err.Error())
return mapList, err
}
defer res.Close()
for res.Next() {
errs := res.Scan(&custResponse.McusmlokPk, &custResponse.McusmlokKode, &custResponse.McusNama)
for _, eachCust := range res {
//the error goes here , for some reason
}
}
return mapList, nil
}
然后我尝试循环该值,然后错误显示我无法在 *sql.rows 的 res 范围内进行范围,如何将这些结果声明为数组而不是 *sql.rows 类型?
解决方案
您需要使用 rows.next 将您的值扫描到一个结构中,您循环查询给出的 sql 结果,您需要将这些结果(在每个循环上)扫描到您想要的结构中,并将该结构保存到某个东西中(在这种情况下是地图)
func getarraylistcustomer(querytype string) (map[string]customermodelresponse, error) {
logger := customlogger.getinstance()
logger.println("service: getarraylistcustomer start")
querytext := dao.customerdao(querytype)
res, err := config.getdbbypath("mydatabase").getdb().query(querytext)
maplist := make(map[string]customermodelresponse)
if config.fancyhandleerror(err) {
logger.println("service: getarraylistcustomer -> error " + err.error())
return maplist, err
}
defer res.close()
for res.next() {
var custresponse customermodelresponse
if err := res.scan(&custresponse.mcusmlokpk, &custresponse.mcusmlokkode, &custresponse.mcusnama); err != nil {
// handle error
}
maplist[cutresponse.mcusmlokpk] = custresponse
}
// now maplist is a map with mcusmlokpk as key and customermodelresponse struct as value
return maplist, nil
}您不能在 res 上使用 for range 循环。 res 只能使用 next() 进行迭代。您可以执行以下操作:
for res.Next() {
//CREATE A NEW ZERO VALUE CustomerModelResponse FOR EACH ITERATION
var custResponse CustomerModelResponse
// UPDATE CustomerModelResponse WITH ROW DATA
errs := res.Scan(&custResponse.McusmlokPk, &custResponse.McusmlokKode, &custResponse.McusNama)
if errs == nil {
// APPEND THE NEWLY CREATED & UPDATED CustomerModelResponse TO mapList
// ASSUMINg mst_customer.mcus_mlok_pk AS KEY FOR THE MAP
mapList[custResponse.McusmlokPk] = custResponse
}
/*
THIS LOOP IS NOT NEEDED ANY MORE
for _, eachCust := range res {
//the error goes here , for some reason
}
*/
}
我希望这会有所帮助。
今天关于《SQL select 查询的循环结果》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.26
11.26
11.26
11.26
11.26
热门专题
