英文:
How to pass values to a variadic parameter in a func from a variadic argument
问题
SQL库函数QueryContext接受可变参数作为where子句。我想创建一个辅助函数,接受可变参数并将其发送给QueryContext调用。
以下是我的代码片段:
func GenericDBSelect(ctx context.Context, qry string, params ...string) (*sql.Rows, error) {
// 格式化连接字符串
db, err := sql.Open("mysql", connectstr)
if err != nil || db == nil {
msg := "无法获取数据库连接。数据库是否可用?"
return nil, fmt.Errorf(msg)
}
rows, err := db.QueryContext(ctx, qry, params)
if err != nil {
msg := fmt.Sprintf("无法准备查询 = %v, 参数 = %v。错误 = %v", qry, params, err)
return nil, fmt.Errorf(msg)
}
return rows, err
}
我这样调用它:
rows, err := GenericDBSelect(ctx, qry, param1, param2)
当我运行这段代码时,它抛出以下错误:
SQL:转换参数$1的类型:不支持类型[]string,一个字符串切片
问题似乎是GenericDBSelect中的params以[]string形式接收,而不是...string形式。
英文:
The SQL library func QueryContext takes variadic parameter for the where clause. I would like to create a helper function that takes variadic parameter and send that to QueryContext call.
Here is my code snippet:
func GenericDBSelect(ctx context.Context, qry string, params ...string) (*sql.Rows, error) {
// format the connectstr
db, err := sql.Open("mysql", connectstr)
if err != nil || db == nil {
msg := "could not get db connection. Is DB available?"
return nil, fmt.Errorf(msg)
}
rows, err := db.QueryContext(ctx, qry, params)
if err != nil {
msg := fmt.Sprintf("Could not prep query = %v, params = %v. Error = %v ", qry, params, err)
return nil, fmt.Errorf(msg)
}
return rows, err
}
And I call it like this:
rows, err := GenericDBSelect(ctx, qry, param1, param2)
When I run this code, it throws the following error:
> SQL: converting argument $1 type: unsupported type []string, a slice of string
The problem seems to be that the params in GenericDBSelect is received as []string instead of ...string.
答案1
得分: 1
进行以下两个更改:
-
声明GenericDBSelect函数接受与QueryContext相同类型的可变参数。这样可以直接传递
params
而无需转换。func GenericDBSelect(ctx context.Context, qry string, params ...any) (*sql.Rows, error) {
-
使用
...
语法将可变参数传递给QueryContext:rows, err := db.QueryContext(ctx, qry, params...)
有关更多信息,请参阅将参数传递给...参数。
英文:
Make these two changes:
-
Declare GenericDBSelect to take the same type of variadic argument as QueryContext. This allows
params
to be passed through with no conversion.func GenericDBSelect(ctx context.Context, qry string, params ...any) (*sql.Rows, error) {
-
Pass the variadic arguments to QueryContext using the
...
syntax:rows, err := db.QueryContext(ctx, qry, params...)
See Passing arguments to ... parameters for more information.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论