gpt4 book ai didi

mysql - 为选择查询传递可变参数

转载 作者:数据小太阳 更新时间:2023-10-29 03:27:53 26 4
gpt4 key购买 nike

我正在尝试按如下方式构建查询,这里我使用的是 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 的长度。我遇到的问题是,一旦我给出 constrains.LocationGroups... 作为选择查询参数,它就会将可变数量的 args 传递给 Select 查询,它会引发编译器错误 too many arguments in call to dbMap.Select

有没有可能实现这种需求?。感谢您的意见。

最佳答案

根据 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
}

在这里,我必须将字符串 slice 转换为接口(interface) slice 。

关于mysql - 为选择查询传递可变参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34552723/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com