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...)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!