为选择查询传递可变参数

时间:2016-01-01 00:39:58

标签: mysql go gorp

我正在尝试按如下方式构建查询,这里我正在使用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

是否有可能达到这种要求?感谢您的意见。

1 个答案:

答案 0 :(得分:0)

根据Pass string slice to variadic empty interface parameter

找到答案

以下是实现任务的更新代码

func GetAgregatedDownloadsFromTo(constrains dao.Constrains) [] dao.NameValue {
    dbMap := utils.GetDBConnection("radsummary");
    defer dbMap.Db.Close()
    var totalDailyDownloads[] dao.NameValue
    query := "SELECT SUM(outputoctets) as value ,date as name FROM dailyacct where date >= ? AND date < ? "

    if len(constrains.LocationGroups) > 0 {
        args := make([]interface{}, len(constrains.LocationGroups)+2)
        args[0] = constrains.From
        args[1] = constrains.To
        for index, value := range constrains.LocationGroups { args[index+2] = value }

        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, args...)
        if err != nil {
            panic(err.Error()) // proper error handling instead of panic
        }
    }
    return totalDailyDownloads
}

这里我必须将字符串切片转换为接口切片。