首页 > 解决方案 > SQL 选择查询的循环结果

问题描述

所以我正在学习 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 类型?

标签: arraysgoarraylist

解决方案


你不能使用for range循环resres只能使用 进行迭代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
        }
    */
}

我希望这有帮助。


推荐阅读