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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里