Home > Software design >  Error when insert using execContext golang
Error when insert using execContext golang

Time:04-13

I have code which will handle inserting new data into database mysql, I have put right context, query Statement, and parameters of value. But when I try to execute the query, I got error like this

sql: expected 1 arguments, got 6

this is my driver

"github.com/go-sql-driver/mysql"

this is my db connection statement

connResult, err := sql.Open("mysql", os.Getenv("MY_SQL_URL"))

and this is my code

func (pr productRepo) AddProduct(c *gin.Context, req product.AddProduct) *model.RepoResponse {
    var negotiate int8
    ctx, cancel := context.WithTimeout(c, 10*time.Second)
    identity := library.Identity(c)
    currentTime := library.Time().CurrentDateTimeDbFormat()

    defer cancel()

    id := uuid.New()
    if req.Negotiate {
        negotiate = 1
    }
    statement := "INSERT INTO product (id_product, user, field, judul, negosiasi, createdAt) VALUES ('?', '?', '?', '?', ?, '?')"

    result, errInsert := pr.conn.ExecContext(ctx, statement, id, identity.GetUserID(), req.Field, req.Title, negotiate, currentTime)
    if errInsert != nil {
        fmt.Println(errInsert)
        return &model.RepoResponse{Success: false, Msg: "Failed to add product"}
    }

    inserted, errRows := result.RowsAffected()
    if errRows != nil {
        fmt.Println(errRows)
        return &model.RepoResponse{Success: false, Msg: "Failed to add product"}
    } else if inserted == 0 {
        fmt.Println("Inserted value ", inserted)
        return &model.RepoResponse{Success: false, Msg: "Failed to add product"}
    }
    return &model.RepoResponse{Success: true, Data: id}
}

Is there any problem in my code or it is from my driver? Thank you

CodePudding user response:

Try to put the question marks in the statement without the apostrophes:

statement := "INSERT INTO product (id_product, user, field, judul, negosiasi, createdAt) VALUES (?, ?, ?, ?, ?, ?)"

As you can see, in your code you have only one ? without the apostrophes, so the driver expects one arg and not six

  • Related