Golang动态绑定变量的数量

huangapple go评论83阅读模式
英文:

Golang dynamic number of bind variables

问题

我一直在使用MyMySQL,目前已经编写了一个API调用,该调用接受可变数量的参数并生成搜索查询。我一直在尝试绑定传入的参数以防止SQL注入,但是我似乎无法弄清楚如何处理可变数量的参数。Bind函数的签名如下:

Bind(params ...interface{})

尽管我猜测这两种解决方案都不会起作用,但我尝试在循环中逐个绑定每个参数,然后还尝试传入一个包含所有参数值的[]interface{}。

有没有办法处理这个问题?结构绑定不起作用,因为每个字段可能有多个值。例如,我可能会传回1个或10个公司ID。

英文:

I've been working with MyMySQL and currently have written an API call that takes a variable number of parameters and generates a search query. I have been trying to bind the passed in parameters to protect against SQL injection, however I cannot seem to figure out how to handle a variable amount of parameters. The Bind function signature looks like:

Bind(params ...interface{})

Although I guessed both solutions wouldn't work, I tried binding each parameter one at a time in a loop, and then also tried passing in a []interface{} containing all of the parameter values.

Is there anyway to handle this solution? Struct binding wont work since I could have multiple values per each field. For instance, I could have 1 or 10 company IDs passed back to me.

答案1

得分: 2

你的第二次尝试接近成功。构建一个名为var foo []interface{}的变量,其中包含所有的参数,并将其作为参数传递给Bind函数。

参考:将参数传递给...参数

英文:

Your second attempt was close to success. Build a, say var foo []interface{} containing all arguments and pass it as

Bind(foo...)

See also Passing arguments to ... parameters

huangapple
  • 本文由 发表于 2013年7月10日 22:28:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/17573298.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定