【问题标题】:How to pass variable ids to statement.Query() in golang?如何将变量 id 传递给 golang 中的 statement.Query()?
【发布时间】:2022-05-03 20:58:49
【问题描述】:

我在 postgres 中有这个查询,它根据传递的参数查询 1 或 n 个用户:

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

现在,当我尝试在 golang 中使用它时,我在处理如何将这种类型的变量参数传递给 statement.Query() 函数时遇到了问题:

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

这会引发错误:Cannot use 'ids' (type []string) as type []interface{}

当我签入源代码查询时,它可以接收许多接口类型的变量:

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

如果我手动执行此操作,它会起作用:

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

但我当然需要 args 为 1 或更多,并且动态生成。

我正在使用 Sqlx 库。

【问题讨论】:

    标签: go sqlx


    【解决方案1】:

    正如我们在Query() 方法方案和错误消息中看到的那样,该方法需要[]interface{} 类型的参数。

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

    在您的代码中,ids 变量保存 []string 数据。将其更改为[]interface{},使其满足Query() 的要求,然后就可以工作了。

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

    【讨论】:

    • 4 年后相关!谢谢!
    猜你喜欢
    • 1970-01-01
    • 2015-05-19
    • 1970-01-01
    • 2021-08-15
    • 1970-01-01
    • 2015-04-19
    • 2021-05-31
    • 2016-02-21
    相关资源
    最近更新 更多