Home > Back-end >  Calling Stored Procedure in GoLang with QueryRowContent
Calling Stored Procedure in GoLang with QueryRowContent

Time:07-21

Im trying to run the below code segment and keeps throwing the below error from QueryRowContext

sql: expected 0 arguments, got 2

This approach works with plain SQL queries and I keep getting the issue when I try to call a Stored Prod to the query param with the CALL keyword.

import (
"database/sql"
"net/http"
)

func VerifyUser(user User) (*User, string, error) {
  db, ctx := db.GetDB()
  query := "CALL usp_GetUserByUsername(@Email)"

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.QueryRowContext(ctx, sql.Named("Email", user.Email))

var retUser User
err = row.Scan(&retUser.ID, &retUser.Email, &retUser.Password, &retUser.Status)
if err != nil {
    log.Warningln("Unknown Email: "   user.Email   ". "   err.Error())
    return nil, "Invalid user.", err
}

What seems to be wrong here? Thanks in advance.

CodePudding user response:

import (
"database/sql"
"net/http"
)

func VerifyUser(user User) (*User, string, error) {
  db, ctx := db.GetDB()
  query := "CALL usp_GetUserByUsername(?)"

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.QueryRowContext(ctx, user.Email)

var retUser User
err = row.Scan(&retUser.ID, &retUser.Email, &retUser.Password, &retUser.Status)
if err != nil {
    log.Warningln("Unknown Email: "   user.Email   ". "   err.Error())
    return nil, "Invalid user.", err
}

Replace @Email in your query with ? and pass the email into QueryRowContext not named statement

  • Related