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 网络科学导论,网络控制
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)