我在 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...)
这会引发错误:无法将“ids”(类型 []string)用作类型 []interface{}
当我 checkin 源代码查询时,它可以接收到许多接口(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 库。
最佳答案
正如我们在 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...)
关于go - 如何将变量 ID 传递给 golang 中的 statement.Query()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52791692/