Variadic argument error while persisting data to DB

Hi,

I am getting error below while executing INSERT query as shown below. What would be the solution or proper way of doing it?

Thanks

sql: converting argument $1 type: unsupported type []interface {}, a slice of interface]

func main() {
    type dto struct {
        name string
        year uint16
    }

    dto := dto{"abc", 123}

    insert(
        "INSERT INTO `user` (`name`, `found`) VALUES (?, ?)",
        dto.name,
        dto.year,
    )
}

func insert(query string, args ...interface{}) int {
    stmt, err := database.Prepare(query) // database is > *sql.DB
    if err != nil {
        panic(err)
    }
    defer stmt.Close()

    res, err := stmt.Exec(args)
    if err != nil {
        panic(err) // This causes error
    }

    id, err := res.LastInsertId()
    if err != nil {
        panic(err)
    }

    return id
}
1 Like

On top of stmt.Exec(args...) following change seems to be required.

insert(
        "INSERT INTO `user` (`name`, `found`) VALUES (?, ?)",
        []interface{}{dto.name,
        dto.year}...,
    )
1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.