猿问

为选择查询传递可变参数

我正在尝试按如下方式构建查询,这里我使用的是 gorp。


func GetAgregatedDownloadsFromTo(constrains Constrains) [] dao.NameValue {

    dbMap := utils.GetDBConnection("radsummary");

    defer dbMap.Db.Close()

    var totalDailyDownloads[] NameValue

    query := "SELECT SUM(outputoctets) as value ,date as name FROM dailyacct where date >= ? AND date < ? "


    if len(constrains.LocationGroups) > 0 {

        query = query + " AND calledstationid=? "

        for i := 1; i< len(constrains.LocationGroups); i++ {

            query = query + " OR calledstationid=? "

        }

        query = query + " group by date"

        print(query)

        _, err := dbMap.Select(&totalDailyDownloads, query, constrains.From, constrains.To, constrains.LocationGroups...)

        if err != nil {

            panic(err.Error()) // proper error handling instead of panic

        }

    }

    return totalDailyDownloads

}


type Constrains struct {

    From string `json:"from"`

    To string   `json:"to"`

    LocationGroups []string    `json:"locationgroups"`

}

查询构造基于 constrains.LocationGroups 的长度发生。我遇到的麻烦是将可变数量的 args 传递给 Select 查询,一旦我给出了 constrains.LocationGroups... 作为选择查询参数,它会引发编译器错误too many arguments in call to dbMap.Select


有没有可能达到这种要求?。感谢您的投入。


慕村9548890
浏览 165回答 1
1回答

MM们

找到了一个基于Pass string slice to variadic empty interface 参数的答案以下是完成任务的更新代码func GetAgregatedDownloadsFromTo(constrains dao.Constrains) [] dao.NameValue {&nbsp; &nbsp; dbMap := utils.GetDBConnection("radsummary");&nbsp; &nbsp; defer dbMap.Db.Close()&nbsp; &nbsp; var totalDailyDownloads[] dao.NameValue&nbsp; &nbsp; query := "SELECT SUM(outputoctets) as value ,date as name FROM dailyacct where date >= ? AND date < ? "&nbsp; &nbsp; if len(constrains.LocationGroups) > 0 {&nbsp; &nbsp; &nbsp; &nbsp; args := make([]interface{}, len(constrains.LocationGroups)+2)&nbsp; &nbsp; &nbsp; &nbsp; args[0] = constrains.From&nbsp; &nbsp; &nbsp; &nbsp; args[1] = constrains.To&nbsp; &nbsp; &nbsp; &nbsp; for index, value := range constrains.LocationGroups { args[index+2] = value }&nbsp; &nbsp; &nbsp; &nbsp; query = query + " AND calledstationid=? "&nbsp; &nbsp; &nbsp; &nbsp; for i := 1; i< len(constrains.LocationGroups); i++ {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; query = query + " OR calledstationid=? "&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; query = query + " group by date"&nbsp; &nbsp; &nbsp; &nbsp; print(query)&nbsp; &nbsp; &nbsp; &nbsp; _, err := dbMap.Select(&totalDailyDownloads, query, args...)&nbsp; &nbsp; &nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; panic(err.Error()) // proper error handling instead of panic&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return totalDailyDownloads}在这里,我不得不将字符串切片转换为接口切片。
随时随地看视频慕课网APP

相关分类

Go
我要回答