arrays - 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 类型?
解决方案
你不能使用for range
循环res
。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
}
*/
}
我希望这有帮助。
推荐阅读
- c++ - 是否可以在 C++ 中基于给定标识符创建基类的新实例,反之亦然
- javascript - 根据矩阵B的排序对矩阵A进行排序
- javascript - 有没有办法在查询构建器的“with”子句中添加计数?
- three.js - 在组件内部的Aframe中导入threejs代码
- php - Laravel 发送带有降价的电子邮件不记录
- mysql - 使用 Inner Join/Group_Concat 更新两个表之间的 Inner Join 返回子查询错误
- angular - 无法在角度中设置未定义的属性?
- c++ - 如何在 Xcode 中定义 DOBJC_OLD_DISPATCH_PROTOTYPES?
- kubernetes - Kubernetes:为 Kafka 创建一个入口
- sql - 在非唯一列中生成唯一 ID