doushangan3690 2018-10-13 09:53
浏览 100
已采纳

如何在Golang中将变量ID传递给statement.Query()?

I have this query in postgres which queries 1 or n users based on the parameters passed:

select name, phone from clients where id in ('id1','id2')

Now when I try to use this at golang I'm having problems approaching how to pass this type of variable arguments to the statement.Query() function:

ids := []string{"0aa6c0c5-e44e-4187-b128-6ae4b2258df0", "606b0182-269f-469a-bb29-26da4fa0302b"}
rows, err := stmt.Query(ids...)

This throws error: Cannot use 'ids' (type []string) as type []interface{}

When I check in source code query it can receive many variables of type interface:

func (s *Stmt) Query(args ...interface{}) (*Rows, error) {
    return s.QueryContext(context.Background(), args...)
}

If I do this manually it works:

rows, err := stmt.Query("0aa6c0c5-e44e-4187-b128-6ae4b2258df0", "606b0182-269f-469a-bb29-26da4fa0302b")

But of course I need the args to be 1 or many more, and dynamically generated.

I'm using Sqlx lib.

  • 写回答

1条回答 默认 最新

  • dpymrcl269187540 2018-10-13 10:07
    关注

    As we can see on the Query() method scheme and also from the error message, the method requires an argument in []interface{} type (variadic interface{}).

    func (s *Stmt) Query(args ...interface{}) (*Rows, error) {
        return s.QueryContext(context.Background(), args...)
    }
    

    In your code, the ids variable hold []string data. Change it to []interface{} so it'll meet Query() requirements, then it'll work.

    ids := []interface{}{"0aa6c0c5-e44e-4187-b128-6ae4b2258df0", "606b0182-269f-469a-bb29-26da4fa0302b"}
    rows, err := stmt.Query(ids...)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果