Golang error: “scannable dest type ptr with >1 columns (4) in result”

项目中的dao层,我们用来查询数据库,获取想要数据。有时我们会需要查询数据给结构体赋值,并返回一个结构体指针,如下

func GetCommunityDetailByID(id int64) (communityDetail *models.CommunityDetail, err error) {
    sqlStr := `SELECT community_id,community_name,introduction,create_time FROM community WHERE community_id = ?`
    if err = db.Get(&communityDetail, sqlStr, id); err != nil {
        if err == sql.ErrNoRows {
            zap.L().Warn("there is no community_id in db.", zap.Error(err))
            err = ErrorInvalidID
        }
    }
    return
}

这样的代码看似没有问题,但其实并不正确,运行结果如下

2022-12-17T13:15:30.008+0800    ERROR   controller/community.go:37      logic.GetCommunityDetail() failed.      {"error": "scannable dest type ptr with >1 columns (4) in result"}

解决方法

出现上面的问题是因为在函数返回值处,我们只是声明了一个指针model.CommunityDetail类型的指针community,要使用这个指针给结构体赋值之前我们需要先对其进行初始化

func GetCommunityDetailByID(id int64) (communityDetail *models.CommunityDetail, err error) {
    communityDetail = new(models.CommunityDetail)
    sqlStr := `SELECT community_id,community_name,introduction,create_time FROM community WHERE community_id = ?`
    if err = db.Get(communityDetail, sqlStr, id); err != nil {
        if err == sql.ErrNoRows {
            zap.L().Warn("there is no community_id in db.", zap.Error(err))
            err = ErrorInvalidID
        }
    }
    return
}

版权声明:
作者:Ne-21
链接:https://blog.gocos.cn/archives/283.html
来源:云淡风轻
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
海报
Golang error: “scannable dest type ptr with >1 columns (4) in result”
项目中的dao层,我们用来查询数据库,获取想要数据。有时我们会需要查询数据给结构体赋值,并返回一个结构体指针,如下 func GetCommunityDetailByID(id int64……
<<上一篇
下一篇>>