使用 execContext golang 插入时出错

我有处理将新数据插入数据库 mysql 的代码,我已经放置了正确的上下文、查询语句和值参数。但是当我尝试执行查询时,出现了这样的错误


sql: expected 1 arguments, got 6

这是我的司机


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

这是我的数据库连接语句


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

这是我的代码


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}

}

我的代码有问题还是我的驱动程序有问题?谢谢


慕丝7291255
浏览 160回答 1
1回答

繁华开满天机

尝试将问号放在没有撇号的语句中:statement := "INSERT INTO product (id_product, user, field, judul, negosiasi, createdAt) VALUES (?, ?, ?, ?, ?, ?)"如您所见,在您的代码中只有一个?没有撇号,因此驱动程序需要一个 arg 而不是六个
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go