英文:
Retrieving set of rows from database : "sql: expected 1 arguments, got 2"
问题
我正在尝试从数据库中检索一组行。我正在映射具有2个匹配变量的结构体。然而,Golang抛出了以下错误。
在运行err = row.Scan(&resourceList)
时出错
>错误信息:"sql: 期望1个参数,但给出了2个"
type Permission struct {
ID int `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
ParentResourceID int `json:"parentResourceId"`
}
func GetResourcesByResourceTypeId(resourceTypeId string) ([]Permission, string, error) {
db, ctx := db.GetDB()
query := "CALL usp_GetParentResourceListByResourceTypeID(?)"
var resourceList []Permission
stmt, err := db.Prepare(query)
if err != nil {
log.Errorln("准备语句时出错:" + err.Error())
return nil, "准备语句时出错。", err
}
defer stmt.Close()
row := stmt.QueryRow(ctx, resourceTypeId)
err = row.Scan(&resourceList)
if err == nil {
return resourceList, "资源检索。", nil
}
log.Warningln("资源检索失败,ResourceTypeID:" + resourceTypeId + "。")
return resourceList, "资源检索失败。", nil
}
SQL返回如下:
ID Name
15 Applications
16 Subscriptions
17 Payments
这里似乎有什么问题?
英文:
I'm trying to retrieve a set of rows from the database. I'm mapping the struct which has 2 matching variables. However, golang throws the below error.
Error occurs when running err = row.Scan(&resourceList)
>s:"sql: expected 1 arguments, got 2"
type Permission struct {
ID int `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
ParentResourceID int `json:"parentResourceId"`
}
func GetResourcesByResourceTypeId(resourceTypeId string) ([]Permission, string, error) {
db, ctx := db.GetDB()
query := "CALL usp_GetParentResourceListByResourceTypeID(?)"
var resourceList []Permission
stmt, err := db.Prepare(query)
if err != nil {
log.Errorln("Error in preparing statement. " + err.Error())
return nil, "Error in preparing statement.", err
}
defer stmt.Close()
row := stmt.QueryRow(ctx, resourceTypeId)
err = row.Scan(&resourceList)
if err == nil {
return resourceList, "Resource retrieval.", nil
}
log.Warningln("Resource retrieval failed, ResourceTypeID: " + resourceTypeId + ".")
return resourceList, "Resource retrieval failed.", nil
}
SQL Returns below
ID Name
15 Applications
16 Subscriptions
17 Payments
What seems to be the issue here?
答案1
得分: 2
Stmt.QueryRow
只应传递要填入预处理语句的参数。由于您将ctx
作为第一个参数传递,它试图将ctx
和resourceTypeId
都填入预处理语句中。这就是为什么您看到"expected 1 arguments, got 2"的原因。您的语句应该只接受一个参数,而您却提供了两个。
如果您想在查询中使用上下文,请改用Stmt.QueryRowContext
。
英文:
Stmt.QueryRow
should only be passed the arguments to be filled into the prepared statement. Since you're passing ctx
as the first argument, it is trying to fill in both ctx
and resourceTypeId
into the prepared statement. That is why you are seeing "expected 1 arguments, got 2". Your statement should only take one argument, and you are giving two.
If you want to use the context in the query, use instead Stmt.QueryRowContext
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论