Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Error when insert using execContext golang

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading