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?
CodePudding user response:
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
.